﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;

public partial class pagedesigner : System.Web.UI.Page
{
    HtmlForm frmObj;
    DynamicDisplayI DDI;
    HDDatabase HDD;

    bool IsEdit = false;
    bool IsCopy = false;
    string strPageKey = "";

    DataTable dt_controldetails = new DataTable();
    DataTable dt_RoleDetails = new DataTable();

    DataTable dtaData = new DataTable();
    DataSet dsePageInfo = new DataSet();
    DataSet dseInputInfo = new DataSet();
    DataTable dt_default_col = new DataTable();

    DataSet dseObjectInputInfo = new DataSet();
    DataSet dsePageInputInfo = new DataSet();
    DataSet dsePagesetInputInfo = new DataSet();

    ArrayList defaultColumns;
    
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        security hdds = new security();
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        string strErrorMsg = "";
        if (!hdds.IsValidPageURL(ref strErrorMsg))
        {
            lblMessage.Text = wrapItAsMessage(strErrorMsg, true);
            TABLE1.Visible = false;
            return;
        }

        HDD = new HDDatabase();
        ScreenReader SR = new ScreenReader();
        if (this.Master.FindControl("Form1") != null)
            frmObj = (HtmlForm)this.Master.FindControl("Form1");

        if (!IsPostBack)
            loadOwneridDropDown();
        CheckForChangeOwner();
        createDefaultColumns();
        checkEditCopyOperation();
        if (!IsPostBack)
            loadPageSettings();
        loadControlDetails();
        loadRoleDetails();
        getpageicons();
        isViewMode();
    }

    #region Page Icon and Tooltip
    private void getpageicons()
    {
        PageIcons icons = new PageIcons();
        HDDatabase Hdd = new HDDatabase();
        try
        {
            string strPagesetRowID = Request.QueryString["pgs_id"].ToString();
            lblHeader.Text = "&nbsp;" + icons.geticontextfrompageset(strPagesetRowID, 2) + "&nbsp;" + lblHeader.Text;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
            lblHeader.Text = "<img src=" + PageIcons.strdefaulticon.ToString() + "></img>&nbsp;" + lblHeader.Text;
        }
        finally
        {
            icons = null;
            Hdd = null;
        }
    }

    private void AddPageToolTip(DataRow drpage, ref Label lblHeader)
    {
        if (drpage != null)
        {
            if (!Page.IsPostBack)
                lblHeader.Text = lblHeader.Text + getTootipIcon(drpage);
            Literal lit = new Literal();
            lit.Text = getTooltipContent(drpage);
            td_Page_ToopTip.Controls.Add(lit);
        }
    }

    private string getTootipIcon(DataRow droPage)
    {
        try
        {
            if (!droPage.Table.Columns.Contains("page_desc")) return "";
            if (droPage["page_desc"].ToString().Trim() == "") return "";
            return "&nbsp;<img id=\"page_tooltip_img\" style=\"cursor:pointer;\" src=\"Images/collapse3.gif\" onClick=\"javascript:showHideTooltipDIV();\" border=\"0\"></img>";
        }
        catch (Exception e)
        {
            return "";
        }
    }

    private string getTooltipContent(DataRow droPage)
    {
        if (!droPage.Table.Columns.Contains("page_desc")) return "";
        if (droPage["page_desc"].ToString().Trim() == "") return "";
        return getContent(HttpContext.Current.Server.MapPath("") + @"\scripts\pagetooltipcontent.txt").Replace("<<content>>", CommonFunctions.SafeEncode(droPage["page_desc"].ToString()));
    }

    private string getContent(string fileName)
    {
        try
        {
            if (!File.Exists(fileName))
                return "";
            string temp = "";
            StreamReader sr = new StreamReader(fileName);
            temp = sr.ReadToEnd();
            sr.Close();
            sr = null;
            return temp;
        }
        catch (Exception e)
        {
            return "";
        }
    }

    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    #endregion

    private bool checkEditCopyOperation()
    {
        try
        {
            if (Request.QueryString["PK"] == null)
                lblHeader.Text = " Page Designer - Add";
            if (Request.QueryString["PK"] != null)
            {
                lblHeader.Text = " Page Designer - Edit";
                lbl_once_save.Text = "Once saved, show the page.";
                IsEdit = true;
                strPageKey = HDD.GetColumnValue("sy_pgs", "pageset_id", "af_row_id = '" + Request.QueryString["PK"].ToString() + "'");
            }
            if (Request.QueryString["CPY"] != null)
                if (Request.QueryString["CPY"] == "0")
                {
                    lblHeader.Text = " Page Designer - Copy";
                    lbl_once_save.Text = "Once saved, create menu and show the page.";
                    IsEdit = false;
                    IsCopy = true;
                }
            if (Request.QueryString["VMODE"] != null)
                if (Request.QueryString["VMODE"] == "1")
                    lblHeader.Text = " Page Designer - View";
            if (IsEdit)
            {
                btnSave.Visible = false;
                btnUpdate.Visible = true;
            }
            else
            {
                btnUpdate.Visible = false;
                btnSave.Visible = true;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("PageDesigner: checkEditCopyOperation : Error : " + ex.Message);
            return true;
        }
        return true;
    }

    private void getandsetData()
    {
        ScreenReader SR = new ScreenReader();
        try
        {
            if (IsEdit && !IsCopy)
            {
                DataRow drPage = HDD.GetTableRow("Select sy_pg.* from sy_pg inner join sy_pgs_mem on sy_pg.page_id = sy_pgs_mem.page_id where sy_pgs_mem.pageset_id  = '" + Request.QueryString["PK"].ToString() + "';");
                DataRow drObj = HDD.GetTableRow("Select sy_obj.* from sy_obj inner join sy_pgs_mem on sy_obj.object_id = sy_pgs_mem.object_id where sy_pgs_mem.pageset_id  = '" + Request.QueryString["PK"].ToString() + "';");
                ps_rowkey.Value = Request.QueryString["PK"].ToString();
                pg_rowkey.Value = drPage["af_row_id"].ToString();
                obj_rowkey.Value = drObj["af_row_id"].ToString();
                ps_id.Value = strPageKey;
                pg_id.Value = drPage["page_id"].ToString();
                obj_id.Value = drObj["object_id"].ToString();
                obj_bu_id.Value = drObj["object_table"].ToString();
                ddl_parent_menu.SelectedValue = HDD.GetColumnValue("select parent_menu_id from sy_mnu where pageset_id = '" + ps_rowkey.Value + "'");

                ddl_template.SelectedValue = drPage["page_view"].ToString();
                txt_page_desc.Text = drPage["page_desc"].ToString();
                txt_controls_per_row.Text = drPage["control_per_row"].ToString();
                cb_caption_row.Checked = Convert.ToBoolean(drPage["first_row_caption_only"].ToString() == "" ? "false" : drPage["first_row_caption_only"].ToString());
                cb_multiple_record.Checked = Convert.ToBoolean(drPage["multiple_recs_page"].ToString() == "" ? "false" : drPage["multiple_recs_page"].ToString());
                cb_section_as_tabs.Checked = Convert.ToBoolean(drPage["sections_as_tabs"].ToString() == "" ? "false" : drPage["sections_as_tabs"].ToString());

                page_owner_id_dd.SelectedValue = drPage["owner_id"].ToString();
                page_owner_id.Value = drPage["owner_id"].ToString();
                LoadEditPage LEP = new LoadEditPage();
                txt_page_owner_id.Text = LEP.GetUserIDFromAfrowid(page_owner_id.Value);

                cb_associate_notes.Checked = Convert.ToBoolean(drObj["associate_notes"].ToString() == "" ? "false" : drObj["associate_notes"].ToString());
                cb_associate_documents.Checked = Convert.ToBoolean(drObj["associate_documents"].ToString() == "" ? "false" : drObj["associate_documents"].ToString());
                cb_associate_task.Checked = Convert.ToBoolean(drObj["associate_task"].ToString() == "" ? "false" : drObj["associate_task"].ToString());

                string selectedvalue = drPage["page_icon"].ToString();
                if (selectedvalue != "")
                    ddl_icon.SelectedValue = selectedvalue;

                if (Request.QueryString["CPY"] != null)
                    txt_page_name.Text = "";
                else
                    txt_page_name.Text = drPage["page_name"].ToString();
            }
            else
            {
                ps_rowkey.Value = SR.getHashKey();
                pg_rowkey.Value = SR.getHashKey();
                obj_rowkey.Value = SR.getHashKey();

                if (IsCopy)
                {
                    DataRow drPage = HDD.GetTableRow("Select sy_pg.* from sy_pg inner join sy_pgs_mem on sy_pg.page_id = sy_pgs_mem.page_id where sy_pgs_mem.pageset_id  = '" + Request.QueryString["PK"].ToString() + "';");
                    DataRow drObj = HDD.GetTableRow("Select sy_obj.* from sy_obj inner join sy_pgs_mem on sy_obj.object_id = sy_pgs_mem.object_id where sy_pgs_mem.pageset_id  = '" + Request.QueryString["PK"].ToString() + "';");
                    string selectedvalue = drPage["page_icon"].ToString();
                    if (selectedvalue != "")
                        ddl_icon.SelectedValue = selectedvalue;
                    ddl_parent_menu.SelectedValue = HDD.GetColumnValue("select parent_menu_id from sy_mnu where pageset_id in (select af_row_id from sy_pgs where pageset_id = '" + strPageKey + "');");
                    ddl_template.SelectedValue = drPage["page_view"].ToString();
                    txt_controls_per_row.Text = drPage["control_per_row"].ToString();
                    cb_caption_row.Checked = Convert.ToBoolean(drPage["first_row_caption_only"].ToString() == "" ? "false" : drPage["first_row_caption_only"].ToString());
                    cb_multiple_record.Checked = Convert.ToBoolean(drPage["multiple_recs_page"].ToString() == "" ? "false" : drPage["multiple_recs_page"].ToString());
                    cb_section_as_tabs.Checked = Convert.ToBoolean(drPage["sections_as_tabs"].ToString() == "" ? "false" : drPage["sections_as_tabs"].ToString());
                    cb_associate_notes.Checked = Convert.ToBoolean(drObj["associate_notes"].ToString() == "" ? "false" : drObj["associate_notes"].ToString());
                    cb_associate_documents.Checked = Convert.ToBoolean(drObj["associate_documents"].ToString() == "" ? "false" : drObj["associate_documents"].ToString());
                    cb_associate_task.Checked = Convert.ToBoolean(drObj["associate_task"].ToString() == "" ? "false" : drObj["associate_task"].ToString());
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("PageDesigner: getandsetData : Error : " + ex.Message);
        }
    }

    private void loadOwneridDropDown()
    {
        try
        {
            if (Request.QueryString["PK"] == null)
            {
                page_owner_id.Value = Session["user_afrowid"].ToString();
                txt_page_owner_id.Text = Session["userid"].ToString();
            }
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] != null)
                {
                    page_owner_id.Value = Session["user_afrowid"].ToString();
                    txt_page_owner_id.Text = Session["userid"].ToString();
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : PageDesigner: loadOwneridDropDown() :" + ex.Message);
        }
    }

    private void CheckForChangeOwner()
    {
        try
        {
            security sec = new security();
            bool status = false;
            status = sec.getRightsForMRUObjects(HttpContext.Current.Request.QueryString["pgs_id"].ToString(), "change_owner");
            if (status == false)
            {
                txt_page_owner_id.Enabled = false;
                imgOwnerSearch.Visible = false;
            }
            sec = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : PageDesigner: CheckForChangeOwner() :" + ex.Message);
        }
    }

    private void loadPageSettings()
    {
        try
        {
            DataTable dt_parent_menu = new DataTable();
            dt_parent_menu = HDD.GetDataTable("select af_row_id, menu_name from sy_mnu order by menu_name;");
            dt_parent_menu.Rows.InsertAt(dt_parent_menu.NewRow(), 0);
            ddl_parent_menu.DataSource = dt_parent_menu;
            ddl_parent_menu.DataTextField = "menu_name";
            ddl_parent_menu.DataValueField = "af_row_id";
            ddl_parent_menu.DataBind();

            string strSql = "Select mem_id, mem_name from sy_acr_mem where acr_id = '438b9d8767ec468a' order by mem_name";
            ddl_template.DataSource = HDD.GetDataTable(strSql);
            ddl_template.DataTextField = "mem_name";
            ddl_template.DataValueField = "mem_id";
            ddl_template.DataBind();
            if (!IsPostBack)
                ddl_template.SelectedValue = "2";

            string strSql1 = "Select mem_id, mem_name from sy_acr_mem where acr_id = '5b8347b08c021f59' order by mem_name";
            ddl_icon.DataSource = HDD.GetDataTable(strSql1);
            ddl_icon.DataTextField = "mem_name";
            ddl_icon.DataValueField = "mem_id";
            ddl_icon.DataBind();
            if (!IsPostBack)
                ddl_icon.SelectedValue = HDD.GetColumnValue("select default_value from sy_pg_ctr where page_id = 'd552d1a32d3d10f9' and control_id = 'page_icon'");

            getandsetData();
            ImgIcon.Src = "Images/MBIcons/medium/" + ddl_icon.SelectedValue;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Page Designer : loadPageSettings() : " + ex.Message);
        }
    }

    private void loadControlDetails()
    {
        try
        {
            DataTable dt_data_bind = new DataTable();
            string sql = applysecurity("Select af_row_id, bind_name from sy_bnd order by bind_name");
            dt_data_bind = HDD.GetDataTable(sql);
            dt_data_bind .Rows.InsertAt(dt_data_bind .NewRow(), 0);
            ddl_data_bind.DataSource = dt_data_bind;
            ddl_data_bind.DataTextField = "bind_name";
            ddl_data_bind.DataValueField = "af_row_id";
            ddl_data_bind.DataBind();

            DataTable dt_format_mask = new DataTable();
            dt_format_mask = HDD.GetDataTable("Select af_row_id, name from sy_format_masks order by name");
            dt_format_mask.Rows.InsertAt(dt_format_mask.NewRow(), 0);
            ddl_format_mask.DataSource = dt_format_mask;
            ddl_format_mask.DataTextField = "name";
            ddl_format_mask.DataValueField = "af_row_id";
            ddl_format_mask.DataBind();


            ddl_field_type.DataSource = HDD.GetDataTable("Select mem_id, mem_name from sy_acr_mem where acr_id = '3f09dcc56a87da14' and mem_value1 = '1' order by mem_name");
            ddl_field_type.DataTextField = "mem_name";
            ddl_field_type.DataValueField = "mem_id";
            ddl_field_type.DataBind();
            ddl_field_type.SelectedValue = "USR";
            if (Session["user_afrowid"].ToString() != "e51e0327224a2eb9")
                ddl_field_type.Enabled = false;

            DataTable dt_ctr_type = new DataTable();
            dt_ctr_type = HDD.GetDataTable("Select mem_id, mem_name from sy_acr_mem where acr_id = 'affbef45c531658c' and mem_value1 = '1' order by mem_name");
            dt_ctr_type.TableName = "CONTROLTYPE";

            DataTable dt_data_type = new DataTable();
            dt_data_type = HDD.GetDataTable("Select mem_id, mem_name from sy_acr_mem where acr_id = '9625e57803931d5b' order by mem_name");
            dt_data_type.TableName = "DATATYPE";

            JavaScriptSerializer js = new JavaScriptSerializer();
            DataSet ds_PageControls = new DataSet();
            ds_PageControls.Tables.Add(dt_ctr_type.Copy());
            ds_PageControls.Tables.Add(dt_data_type.Copy());
            hf_controltype_datatype.Value = js.Serialize(JsonMethods.ToJson(ds_PageControls)).ToString();

            int NoOfControls = 6;
            if (hf_NoOfControls.Value != "")
                NoOfControls = Convert.ToInt32(hf_NoOfControls.Value);

            dt_controldetails.Clear();
            if (!IsEdit && !IsCopy)
            {
                dt_controldetails.Columns.Add("pg_ctr_row_id");
                dt_controldetails.Columns.Add("obj_att_row_id");
                dt_controldetails.Columns.Add("ctr_owner");
                dt_controldetails.Columns.Add("txt_name");
                dt_controldetails.Columns.Add("txt_desc");
                dt_controldetails.Columns.Add("txt_seq");
                dt_controldetails.Columns.Add("ddl_ctr_type");
                dt_controldetails.Columns.Add("ddl_data_type");
                dt_controldetails.Columns.Add("txt_control_id");
                dt_controldetails.Columns.Add("ddl_visible", typeof(bool));
                dt_controldetails.Columns.Add("ddl_is_read", typeof(bool));
                dt_controldetails.Columns.Add("ddl_in_list", typeof(bool));
                dt_controldetails.Columns.Add("txt_size");
                dt_controldetails.Columns.Add("txt_default_value");
                dt_controldetails.Columns.Add("ddl_is_unique", typeof(bool));
                dt_controldetails.Columns.Add("ddl_filter", typeof(bool));
                dt_controldetails.Columns.Add("txt_tooltip");
                dt_controldetails.Columns.Add("ddl_data_bind");
                dt_controldetails.Columns.Add("ddl_format_mask");
                dt_controldetails.Columns.Add("ddl_new_section", typeof(bool));
                dt_controldetails.Columns.Add("ddl_search", typeof(bool));
                dt_controldetails.Columns.Add("txt_section_name");
                dt_controldetails.Columns.Add("ddl_field_type");
            }
            else
            {
                string sql_data = "select [pg_ctr].[af_row_id] as [pg_ctr_row_id], [obj_att].[af_row_id] as [obj_att_row_id], [pg_ctr].[owner_id] as [ctr_owner], " +
                                    "[pg_ctr].[control_name] as [txt_name], [obj_att].[attrib_description] as [txt_desc], [pg_ctr].[control_seq] as [txt_seq], [pg_ctr].[control_html] as [ddl_ctr_type], [pg_ctr].[control_attrib_type] as [ddl_data_type], " +
                                    "[pg_ctr].[control_id] as [txt_control_id], [pg_ctr].[control_visible] as [ddl_visible], [pg_ctr].[read_only] as [ddl_is_read], [srh].[list_flag] as [ddl_in_list], [obj_att].[attrib_size] as [txt_size], " +
                                    "[pg_ctr].[default_value] as [txt_default_value], [obj_att].[is_primary] as [ddl_is_unique], [srh].[quick_search] as [ddl_filter], [obj_att].[object_tooltip] as [txt_tooltip], [pg_ctr].[control_bind_id] as [ddl_data_bind], " +
                                    "[pg_ctr].[input_mask_format] as [ddl_format_mask], [pg_ctr].[is_section] as [ddl_new_section], [pg_ctr].[is_search] as [ddl_search], [pg_ctr].[section_name] as [txt_section_name], [obj_att].[field_type] as [ddl_field_type] " +
                                    "from [sy_pg_ctr] [pg_ctr] " +
                                    "inner join [sy_pg] [pg] on [pg].[af_row_id] = [pg_ctr].[page_id] " +
                                    "inner join [sy_pgs_mem] [mem] on [pg].[page_id] = [mem].[page_id] " +
                                    "inner join [sy_obj] [obj] on [obj].[object_id] = [mem].[object_id] " +
                                    "inner join [sy_obj_att] [obj_att] on [obj].[af_row_id] = [obj_att].[object_id] and [obj_att].[attrib_id] = [pg_ctr].[control_id] " +
                                    "left join [sy_pgs_srh] [srh] on [srh].[pageset_id] = [mem].[pageset_id] and [srh].[search_attrib_id] = [pg_ctr].[control_id] " +
                                    "where [mem].[pageset_id] = '" + Request.QueryString["PK"].ToString() + "' " +
                                    "and [pg_ctr].[control_id] not in ('created_by','created_at','modified_at','modified_by','owner_id','af_row_id') " +
                                    "and [obj_att].[attrib_id] not in ('created_by','created_at','modified_at','modified_by','owner_id','af_row_id') " +
                                    "order by [pg_ctr].[control_seq] asc, [pg_ctr].[control_name] asc;";
                dt_controldetails = HDD.GetDataTable(sql_data);
            }
            dt_controldetails.Columns.Add("ta_droplist"); // Added by 'Imran Gani' on 26-Dec-2013, for droplist values.
            loadControlDroplist(dt_controldetails); // Added by 'Imran Gani' on 26-Dec-2013, for droplist values.
            if (dt_controldetails != null)
            {
                dt_controldetails.TableName = "CONTROLDETAILS";
                if (dt_controldetails.Rows.Count < NoOfControls)
                {
                    NoOfControls = NoOfControls - dt_controldetails.Rows.Count;
                    for (int i = 0; i < NoOfControls; i++)
                    {
                        DataRow dr_new = dt_controldetails.NewRow();
                        dr_new["ddl_visible"] = true;
                        dr_new["ddl_is_read"] = false;
                        dr_new["ddl_in_list"] = true;
                        dr_new["ddl_is_unique"] = false;
                        dr_new["ddl_filter"] = false;
                        dr_new["ddl_new_section"] = false;
                        dr_new["ddl_search"] = false;
                        dt_controldetails.Rows.Add(dr_new);
                    }
                    NoOfControls = dt_controldetails.Rows.Count;
                }
                else
                    NoOfControls = dt_controldetails.Rows.Count;
            }
            hf_NoOfControls.Value = NoOfControls.ToString(); // Added by 'Imran Gani' on 05-Feb-2014, for additional control in edit mode.
            if (!IsPostBack)
                hf_controldetails_json.Value = js.Serialize(JsonMethods.ToJson(dt_controldetails)).ToString();

            for (int i = 0; i < NoOfControls; i++)
            {
                HtmlTableRow tr = new HtmlTableRow();
                HtmlTableCell td = new HtmlTableCell();
                TextBox txt_name = new TextBox();
                txt_name.ID = "txt_name_" + i;
                txt_name.CssClass = "controlFont";
                if (IsEdit || IsCopy)
                    txt_name.Text = dt_controldetails.Rows[i]["txt_name"].ToString();
                td.Controls.Add(txt_name);
                tr.Controls.Add(td);
                
                td = new HtmlTableCell();
                TextBox txt_desc = new TextBox();
                txt_desc.ID = "txt_desc_" + i;
                txt_desc.CssClass = "controlFont";
                txt_desc.Attributes.Add("onfocus", "javascript:getDescFromName(this);");
                if (IsEdit || IsCopy)
                    txt_desc.Text = dt_controldetails.Rows[i]["txt_desc"].ToString();
                td.Controls.Add(txt_desc);
                tr.Controls.Add(td);
                
                td = new HtmlTableCell();
                TextBox txt_seq = new TextBox();
                txt_seq.ID = "txt_seq_" + i;
                txt_seq.CssClass = "controlFont";
                txt_seq.Width = 60;
                if (IsEdit || IsCopy)
                    txt_seq.Text = dt_controldetails.Rows[i]["txt_seq"].ToString();
                td.Controls.Add(txt_seq);
                tr.Controls.Add(td);

                td = new HtmlTableCell();
                DropDownList ddl_ctr_type = new DropDownList();
                ddl_ctr_type.ID = "ddl_ctr_type_" + i;
                ddl_ctr_type.CssClass = "controlFont";
                ddl_ctr_type.Width = 80;
                ddl_ctr_type.DataSource = dt_ctr_type;
                ddl_ctr_type.DataTextField = "mem_name";
                ddl_ctr_type.DataValueField = "mem_id";
                ddl_ctr_type.DataBind();
                ddl_ctr_type.SelectedValue = "TB";
                if ((IsEdit || IsCopy) && dt_controldetails.Rows[i]["ddl_ctr_type"].ToString() != "")
                    ddl_ctr_type.SelectedValue = dt_controldetails.Rows[i]["ddl_ctr_type"].ToString();
                td.Controls.Add(ddl_ctr_type);
                tr.Controls.Add(td);

                td = new HtmlTableCell();
                DropDownList ddl_data_type = new DropDownList();
                ddl_data_type.ID = "ddl_data_type_" + i;
                ddl_data_type.CssClass = "controlFont";
                ddl_data_type.Width = 80;
                ddl_data_type.DataSource = dt_data_type;
                ddl_data_type.DataTextField = "mem_name";
                ddl_data_type.DataValueField = "mem_id";
                ddl_data_type.DataBind();
                ddl_data_type.SelectedValue = "TX";
                if ((IsEdit || IsCopy) && dt_controldetails.Rows[i]["ddl_data_type"].ToString() != "")
                    ddl_data_type.SelectedValue = dt_controldetails.Rows[i]["ddl_data_type"].ToString();
                td.Controls.Add(ddl_data_type);
                tr.Controls.Add(td);

                td = new HtmlTableCell();
                td.Align = "right";
                Image img_delete = new Image();
                img_delete.ID = "img_delete_" + i;
                img_delete.ToolTip = "Delete Control";
                img_delete.AlternateText = "Delete Control";
                img_delete.Style.Add("cursor", "pointer");
                img_delete.ImageUrl = "Images/control_delete.png";
                //img_delete.Attributes.Add("onclick", "javascript:showHideDIVcontrolproeprty(this);");
                if (dt_controldetails.Rows[i]["txt_name"].ToString() == "")
                    img_delete.Attributes.Add("style", "display:none;");
                if (HttpContext.Current.Request.QueryString["VMODE"] != null)
                    if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
                        img_delete.Visible = false;
                td.Controls.Add(img_delete);
                td.Controls.Add(new LiteralControl("&nbsp;"));
                Image img_property = new Image();
                img_property.ID = "img_property_" + i;
                img_property.ToolTip = "Control Property";
                img_property.AlternateText = "Control Property";
                img_property.Style.Add("cursor", "pointer");
                img_property.ImageUrl = "Images/control_property.png";
                //img_property.Attributes.Add("onclick", "javascript:showHideDIVcontrolproeprty(this);");
                if (HttpContext.Current.Request.QueryString["VMODE"] != null)
                    if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
                        img_property.Visible = false;
                td.Controls.Add(img_property);
                td.Controls.Add(new LiteralControl("&nbsp;"));
                tr.Controls.Add(td);
                // To handle extended field support
                if (dt_controldetails.Rows[i]["ddl_field_type"].ToString() != "" && dt_controldetails.Rows[i]["ddl_field_type"].ToString() != "USR" && Session["user_afrowid"].ToString() != "e51e0327224a2eb9")
                {
                    txt_name.Enabled = false;
                    txt_desc.Enabled = false;
                    txt_seq.Enabled = false;
                    ddl_ctr_type.Enabled = false;
                    ddl_data_type.Enabled = false;
                    img_delete.Visible = false;
                    img_property.Visible = false;
                }
                td_controlgrid.Controls.Add(tr);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Page Designer : loadControlDetails() : " + ex.Message);
        }
    }

    private string applysecurity(string sql)
    {
        try
        {
            SecurityFilter objSec = new SecurityFilter();
            string sAFAdmin = objSec.QueryForAFAdmin();
            string sCustodianFilter = objSec.QueryForCustodianFilter();
            if (sCustodianFilter.Trim() != "")
                if (!sCustodianFilter.StartsWith("or"))
                    sAFAdmin += " and " + sCustodianFilter;
                else
                    sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";

            if (sql.Contains("order by"))
            {
                if (sAFAdmin.Trim() != "")
                    sql = sql.Replace("order by", "where " + sAFAdmin + " order by");
            }
            else
            {
                if (sAFAdmin.Trim() != "")
                    sql = sql + " where " + sAFAdmin;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Page Designer: applysecurity : Error : " + ex.Message);
            return sql;
        }
        return sql;
    }

    private void loadRoleDetails()
    {
        string strRolePgsID = "";
        try
        {
            if (Request.QueryString["PK"] != null)
                strRolePgsID = Request.QueryString["PK"].ToString();

            //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
            SecurityFilter objSec = new SecurityFilter();
            string sAFAdmin = objSec.QueryForAFAdmin();
            string modelConString = "";
            modelConString = HttpContext.Current.Session["servercon"].ToString();
            string str_OwnerId = "";
            //string str_BusinessUnit = "";
            if (HttpContext.Current.Session["dbcon"].ToString() != modelConString && sAFAdmin != "")
            {
                BusinessUnit.Access ACS = new BusinessUnit.Access(HttpContext.Current.Session["userid"].ToString(), HDD.GetConnection().ConnectionString, "p_rol");
                str_OwnerId = ACS.AccessableOwners;
                //str_BusinessUnit = ACS.AccessableBuUnits;
            }
            string sCustodianFilter = ""; //= objSec.QueryForCustodianFilter();
            if (sCustodianFilter.Trim() != "")
                if (!sCustodianFilter.StartsWith("or"))
                {
                    if (sAFAdmin.Trim() != "")
                        sAFAdmin = "(" + sAFAdmin + " and " + sCustodianFilter + ") ";
                    else
                        sAFAdmin = "(" + sCustodianFilter + ") ";
                }
                else
                {
                    if (sAFAdmin.Trim() != "")
                        sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                    else
                        sAFAdmin = "(" + sCustodianFilter + ") ";
                }
            objSec = null;
            string str_Filter = sAFAdmin;
            if (sAFAdmin != "")
                str_Filter += str_OwnerId;
            else
                str_Filter += (str_OwnerId == "" ? "" : " " + str_OwnerId.Remove(0, 5) + " ");
            str_Filter += (str_Filter.Trim() == "" ? "" : " or owner_id is null ");
            //if (sAFAdmin != "")
            //    str_Filter += str_BusinessUnit;
            //else
            //    str_Filter += " " + str_BusinessUnit + " ";
            //----------------End for Org Security------------------

            string sql = "select [obj_acc].[af_row_id] as [obj_acc_af_row_id], [rol].[af_row_id] as [rol_af_row_id], [rol].[role_name], [obj_acc].[read], [obj_acc].[create], [obj_acc].[edit], [obj_acc].[delete], [obj_acc].[change_owner] from [sy_rol] [rol] " +
                //"left outer join [sy_rol_acc] [rol_acc] on [rol].[af_row_id] = [rol_acc].[role_id]  and [rol_acc].[menu_id] in (select [menu_id] from [sy_mnu] where [pageset_id] in (select [pageset_id] from [sy_pgs] where [af_row_id] = '" + strRolePgsID + "' )) " + // To include menu rights
                        "left outer join [sy_obj_acc] [obj_acc] on [rol].[af_row_id] = [obj_acc].[role_id] and [obj_acc].[object_id] in (select [object_id] from [sy_pgs_mem] where [pageset_id] = '" + strRolePgsID + "') " +
                        "where " + (str_Filter.Trim() == "" ? "1=1" : str_Filter.Replace("owner_id", "[rol].[owner_id]")) + " order by [rol].[modified_at];";
            dt_RoleDetails = HDD.GetDataTable(sql);

            if (dt_RoleDetails.Rows.Count == 0)
            {
                lbl_RoleMsg.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission for Role Security.", true);
                tb_rolesecurity.Visible = false;
            }

            bool isView = false;
            if (HttpContext.Current.Request.QueryString["VMODE"] != null)
                if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
                    isView = true;

            HtmlTableRow htr = null;
            HtmlTableCell htc = null;

            for (int i = 0; i < dt_RoleDetails.Rows.Count; i++)
            {
                DataRow dr = dt_RoleDetails.Rows[i];
                int intRow = i % 2;

                htr = new HtmlTableRow();
                htr.VAlign = "middle";
                htr.Height = "25px";
                htr.Attributes.Add("Class", "Grid_Row" + intRow.ToString());
                htr.Attributes.Add("onMouseOver", "this.className='Grid_Scroll_BG'");
                htr.Attributes.Add("onMouseOut", "this.className='" + "Grid_Row" + intRow.ToString() + "'");

                htc = new HtmlTableCell();
                htc.VAlign = "middle";
                htc.Align = "left";
                htc.Width = "45%";
                htc.Controls.Add(new LiteralControl("&nbsp;"));
                htc.Controls.Add(new LiteralControl(dr["role_name"].ToString()));
                htr.Cells.Add(htc);

                //htc = new HtmlTableCell();
                //htc.VAlign = "middle";
                //htc.Align = "left";
                //htc.Width = "10%";
                //CheckBox chk_menu = new CheckBox();
                //chk_menu.ID = "chk_menu_" + dr["af_row_id"].ToString();
                //if (dr["menu"].ToString() != "" && dr["menu"].ToString() != "False")
                //    chk_menu.Checked = true;
                //if (isView) chk_menu.Enabled = false;
                //htc.Controls.Add(chk_menu);
                //htr.Cells.Add(htc);

                htc = new HtmlTableCell();
                htc.VAlign = "middle";
                htc.Align = "left";
                htc.Width = "10%";
                CheckBox chk_read = new CheckBox();
                chk_read.ID = "chk_read_" + dr["rol_af_row_id"].ToString();
                htc.Controls.Add(chk_read);
                htr.Cells.Add(htc);

                htc = new HtmlTableCell();
                htc.VAlign = "middle";
                htc.Align = "left";
                htc.Width = "10%";
                CheckBox chk_create = new CheckBox();
                chk_create.ID = "chk_create_" + dr["rol_af_row_id"].ToString();
                htc.Controls.Add(chk_create);
                htr.Cells.Add(htc);

                htc = new HtmlTableCell();
                htc.VAlign = "middle";
                htc.Align = "left";
                htc.Width = "10%";
                CheckBox chk_edit = new CheckBox();
                chk_edit.ID = "chk_edit_" + dr["rol_af_row_id"].ToString();
                htc.Controls.Add(chk_edit);
                htr.Cells.Add(htc);

                htc = new HtmlTableCell();
                htc.VAlign = "middle";
                htc.Align = "left";
                htc.Width = "10%";
                CheckBox chk_delete = new CheckBox();
                chk_delete.ID = "chk_delete_" + dr["rol_af_row_id"].ToString();
                htc.Controls.Add(chk_delete);
                htr.Cells.Add(htc);

                htc = new HtmlTableCell();
                htc.VAlign = "middle";
                htc.Align = "left";
                htc.Width = "15%";
                CheckBox chk_change_owner = new CheckBox();
                chk_change_owner.ID = "chk_change_owner_" + dr["rol_af_row_id"].ToString();
                htc.Controls.Add(chk_change_owner);
                htr.Cells.Add(htc);

                if (!IsPostBack)
                {
                    if (IsEdit)
                    {
                        if (dr["read"].ToString() != "" && dr["read"].ToString() != "False")
                            chk_read.Checked = true;
                        if (dr["create"].ToString() != "" && dr["create"].ToString() != "False")
                            chk_create.Checked = true;
                        if (dr["edit"].ToString() != "" && dr["edit"].ToString() != "False")
                            chk_edit.Checked = true;
                        if (dr["delete"].ToString() != "" && dr["delete"].ToString() != "False")
                            chk_delete.Checked = true;
                        if (dr["change_owner"].ToString() != "" && dr["change_owner"].ToString() != "False")
                            chk_change_owner.Checked = true;
                    }
                    else if (dr["rol_af_row_id"].ToString() == HttpContext.Current.Session["roleid"].ToString())
                    {
                        chk_read.Checked = true;
                        chk_create.Checked = true;
                        chk_edit.Checked = true;
                        chk_delete.Checked = true;
                        chk_change_owner.Checked = true;
                    }
                    if (isView)
                    {
                        chk_read.Enabled = false;
                        chk_create.Enabled = false;
                        chk_edit.Enabled = false;
                        chk_delete.Enabled = false;
                        chk_change_owner.Enabled = false;
                    }
                }
                tb_rolesecurity.Rows.Add(htr);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Page Designer: loadRoleDetails : Error : " + ex.Message);
        }
    }

    private void isViewMode()
    {
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                DynamicDisplayI ddi = new DynamicDisplayI();
                HtmlTable ht = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("TABLE1");
                ddi.disableControls(ht);
                ddi = null;
                img_addcontrol.Visible = false;
            }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (txt_page_name.Text != "")
            savePage();
        else
            lbl_pageid.Text = "This is required field ! ";
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (txt_page_name.Text != "")
            savePage();
        else
            lbl_pageid.Text = "This is required field ! ";
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Redirect(Request.Url.ToString());
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Page Designer : btnReset_Click() : " + ex.Message);
        }
    }

    private DataTable getControlList()
    {
        DataTable dt_Json = new DataTable();
        DataTable dt_controls = new DataTable();
        try
        {
            if (hf_controldetails_json.Value == "")
                return dt_Json;
            dt_Json = JsonFunctions.JsonFunctions.JsonToDataTable(hf_controldetails_json.Value);
            dt_controls = dt_Json.Clone();
            foreach (DataRow dr in dt_Json.Select("txt_name <> ''"))
            {
                dr["txt_name"] = GenerateName(dr["txt_name"].ToString());
                dr["ddl_ctr_type"] = (dr["ddl_ctr_type"].ToString() == "" ? "TB" : dr["ddl_ctr_type"].ToString());
                dr["ddl_data_type"] = (dr["ddl_data_type"].ToString() == "" ? "TX" : dr["ddl_data_type"].ToString());
                if (dr["txt_control_id"].ToString().Trim() == "")
                    dr["txt_control_id"] = GenerateID(dr["txt_name"].ToString());
                else
                    dr["txt_control_id"] = GenerateID(dr["txt_control_id"].ToString());

                string str = dr["ddl_visible"].ToString();
                dr["ddl_visible"] = (str == "1" ? "True" : (str == "0" ? "False" : (str == "" ? "True" : str)));
                str = dr["ddl_is_read"].ToString();
                dr["ddl_is_read"] = (str == "1" ? "True" : (str == "0" ? "False" : (str == "" ? "False" : str)));
                str = dr["ddl_in_list"].ToString();
                dr["ddl_in_list"] = (str == "1" ? "True" : (str == "0" ? "False" : (str == "" ? "True" : str)));
                str = dr["ddl_is_unique"].ToString();
                dr["ddl_is_unique"] = (str == "1" ? "True" : (str == "0" ? "False" : (str == "" ? "False" : str)));
                str = dr["ddl_filter"].ToString();
                dr["ddl_filter"] = (str == "1" ? "True" : (str == "0" ? "False" : (str == "" ? "False" : str)));
                str = dr["ddl_new_section"].ToString();
                dr["ddl_new_section"] = (str == "1" ? "True" : (str == "0" ? "False" : (str == "" ? "False" : str)));
                str = dr["ddl_search"].ToString();
                dr["ddl_search"] = (str == "1" ? "True" : (str == "0" ? "False" : (str == "" ? "False" : str)));

                dt_controls.ImportRow(dr);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Page Designer : btnReset_Click() : " + ex.Message);
        }
        return dt_controls;
    }

    private void savePage()
    {
        try
        {
            if (IsCopy || !IsEdit)
            {
                //txtpsid.Text = GenerateID(txt_page_name.Text);
                ps_id.Value = GenerateID(txt_page_name.Text);
                string isexits = HDD.GetColumnValue("sy_pgs", "pageset_id", "pageset_id = '" + ps_id.Value.Replace("'", "''") + "'");
                if (isexits.Trim().Length > 0)
                {
                    lbl_pageid.Text = "Page already exists! ";
                    return;
                }
                pg_id.Value = "p_" + GenerateID(txt_page_name.Text);
                obj_id.Value = "ob_" + GenerateID(txt_page_name.Text);
                obj_bu_id.Value = "bu_" + GenerateID(txt_page_name.Text); //Dont Change it By Dhanapal_Jan_11_2011
                //obj_bu_id.Value = "sy_" + GenerateID(txt_page_name.Text);
            }
            dt_controldetails = getControlList();
            if(dt_controldetails == null || dt_controldetails.Rows.Count == 0)
                lblMessage.Text = wrapItAsMessage((IsEdit == true ? "Updation" : "Insertion") + " not successful. Provide control details.", true);
            string message3 = "";
            if (validateOwnerid(ref message3))
            {
                string message = "";
                if (validateDataType(ref message))
                {
                    GetDataset();
                    ModifyDataSets();

                    string message2 = "";
                    if (MergePageset(ref message2))
                    {
                        dseObjectInputInfo = null;
                        dsePageInputInfo = null;
                        dsePagesetInputInfo = null;
                        string refURL = getRefURL();
                        string strMenuRowId = string.Empty;
                        if (IsEdit)
                        {
                            strMenuRowId = HDD.GetColumnValue("select af_row_id from sy_mnu where pageset_id in (select af_row_id from sy_pgs where pageset_id = '" + ps_id.Value + "');");
                            if (cb_once_save.Checked && strMenuRowId == "")
                                strMenuRowId = createMenuForPage();
                            else if (strMenuRowId != "")
                                updateParentMenuID(strMenuRowId);
                        }
                        else if (cb_once_save.Checked)
                            strMenuRowId = createMenuForPage();
                        
                        getRoleSecurity(strMenuRowId);

                        if (cb_once_save.Checked)
                            Response.Redirect("DisplayGrid.aspx?pgs_id=" + ps_rowkey.Value + "&mn=" + strMenuRowId);
                        else if (refURL.Length > 0)
                            Response.Redirect(refURL);
                        else
                            lblMessage.Text = wrapItAsMessage("Data Inserted Successfully", false);
                    }
                    else
                        lblMessage.Text = wrapItAsMessage((IsEdit == true ? "Updation" : "Insertion") + " not successful. " + message2, true);
                }
                else
                    lblMessage.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;" + (IsEdit == true ? "Updation" : "Insertion") + " not successful. " + message, true);
            }
            else
                lblMessage.Text = wrapItAsMessage((IsEdit == true ? "Updation" : "Insertion") + " not successful. " + message3, true);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Page Designer : savePage() : " + ex.Message);
        }
    }

    private bool validateOwnerid(ref string message)
    {
        bool status = false;
        BindControl BC = new BindControl();
        DataSet dsBind = new DataSet();
        try
        {
            string sql = BC.GetBindSql("f496930dfe0b690f");
            dsBind = HDD.GetDataset(sql);
            if (dsBind != null)
            {
                if (dsBind.Tables.Count > 0)
                {
                    if (dsBind.Tables[0].Rows.Count > 0)
                    {
                        if (txt_page_owner_id.Text != "")
                        {
                            DataRow[] drrbind = dsBind.Tables[0].Select("fld = '" + txt_page_owner_id.Text.Trim().Replace("'", "''") + "'");
                            if (drrbind.Length > 0)
                            {
                                page_owner_id.Value = drrbind[0]["val"].ToString();
                                status = true;
                            }
                        }
                        else
                        {
                            page_owner_id.Value = "";
                            status = true;
                        }
                    }
                    else
                    {
                        page_owner_id.Value = "";
                        status = true;
                    }
                }
            }
            if (!status)
                message = "Invalid data for Owner :" + HttpUtility.HtmlEncode(txt_page_owner_id.Text);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Page Designer : validateOwnerid() : " + ex.Message);
        }
        return status;
    }

    private string GenerateID(string strid)
    {
        CommonFunctions comm = new CommonFunctions();
        strid = comm.RemoveSpecialCharacters(strid);
        #region Old code for handling special characters, Commented by 'Imran Gani' on 24-Jun-2013
        //char[] trim = { '=', '\\', ';', '.', ':', ',', '+', '*', '\'', '/', '!', '-' };
        //int pos;

        //strid = strid.ToLower();
        //strid = strid.Trim();

        //while ((pos = strid.IndexOfAny(trim)) >= 0)
        //{
        //    strid = strid.Remove(pos, 1);
        //}
        #endregion
        strid = strid.Trim();
        strid = strid.Replace(' ', '_');
        return strid;
    }

    private string GenerateName(string strid)
    {
        char[] trim = { '=', '\\', ';', '.', ':', ',', '+', '*', '\'', '/' };
        int pos;

        strid = strid.Trim();
        while ((pos = strid.IndexOfAny(trim)) >= 0)
        {
            strid = strid.Remove(pos, 1);
        }
        strid = strid.Trim();
        return strid;
    }

    private void createDefaultColumns()
    {
        dt_default_col = new DataTable();
        DataRow dtr;
        defaultColumns = new ArrayList();

        try
        {
            dt_default_col = HDD.GetDataTable("select * from sy_acr_mem where acr_id='cee69885ce44589c' order by mem_seq");
            dtr = dt_default_col.NewRow();
            dtr.ItemArray = dt_default_col.Rows[0].ItemArray;
            dtr[2] = "af_row_id";
            dtr[4] = "af_row_id";
            dt_default_col.Rows.Add(dtr);

            foreach (DataRow dr in dt_default_col.Rows)
            {
                defaultColumns.Add(dr["mem_id"].ToString());
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in createDefaultColumns function. Error: " + e.Message);
        }
    }

    private bool validateDataType(ref string message)
    {
        bool returnFlag = true;
        foreach (DataRow dr in dt_controldetails.Rows)
        {
            int size;
            if (int.TryParse(dr["txt_size"].ToString().Trim(), out size) == false)
                size = 0;
            if ((dr["ddl_data_type"].Equals("TX")) && (size > 4000))
            {
                message = "The size (" + dr["txt_size"].ToString() + ") given to the control '" + dr["txt_name"].ToString() + "' exceeds the maximum allowed(4000).";
                returnFlag = false;
                break;
            }
        }
        return returnFlag;
    }

    private bool GetDataset()
    {
        string[,] pagearr = pagearr = new string[,] 
            {
                {"Object", "9ec6aa32504a516b"}, // ps_dobj
                {"Object", "cdb0ecf826945479"}, // ps_dobj_att

                {"Page", "50f21749fc3da2ee"}, // ps_page
                {"Page", "534b6e11207db844"}, // ps_pg_ctr
                {"Page", "3b58ce68486728f4"}, // pg_ctr_droplist // Added by 'Imran Gani' on 26-Dec-2013, for droplist values.
               
                {"Pageset", "b3ef063b174e4ccc"}, // ps_pageset
                {"Pageset", "a40f400c6424ef4e"}, // ps_pgs_mem
                {"Pageset", "be2f0230028f06a6"} // ps_pgs_srh
            };
        DDI = new DynamicDisplayI();
        string strPagesetRowID;
        bool Status = false;

        for (int j = 0; j <= pagearr.GetUpperBound(0); j++)
        {
            ScreenReader SR = new ScreenReader();
            Master MA = new Master();
            PageInfoLoad PIL = new PageInfoLoad();

            strPagesetRowID = pagearr[j, 1].ToString();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);

            DataTable dtaPageSet = dsePageInfo.Tables["PageSet"];
            DataTable dtaPage = dsePageInfo.Tables["Page"];
            DataTable dtaPageKeys = dsePageInfo.Tables["PageKeys"];
            DataTable dtaPageCtrl = dsePageInfo.Tables["PageCtrl"];

            //if ((strPagesetRowID == "ps_dobj") || (strPagesetRowID == "ps_dobj_att"))
            if ((strPagesetRowID == "9ec6aa32504a516b") || (strPagesetRowID == "cdb0ecf826945479"))
            {
                if (dseObjectInputInfo.Tables.Contains(dtaPage.Rows[0]["page_id"].ToString()) == false)
                    SR.CreatePageDataTable(dseObjectInputInfo, dtaPage, dtaPageCtrl);
                GetDataset(dseObjectInputInfo, strPagesetRowID, dtaPage, dtaPageCtrl);
                //Session["dseObjectInputInfo"] = dseObjectInputInfo;
            }
            //else if ((strPagesetRowID == "ps_page") || (strPagesetRowID == "ps_pg_ctr") || (strPagesetRowID == "ps_pg_key") || (strPagesetRowID == "pg_ctr_droplist")) // Added by 'Imran Gani' on 26-Dec-2013, for droplist values.
            else if ((strPagesetRowID == "50f21749fc3da2ee") || (strPagesetRowID == "534b6e11207db844") || (strPagesetRowID == "ps_pg_key") || (strPagesetRowID == "3b58ce68486728f4")) // Added by 'Imran Gani' on 26-Dec-2013, for droplist values.
            {
                if (dsePageInputInfo.Tables.Contains(dtaPage.Rows[0]["page_id"].ToString()) == false)
                    SR.CreatePageDataTable(dsePageInputInfo, dtaPage, dtaPageCtrl);
                GetDataset(dsePageInputInfo, strPagesetRowID, dtaPage, dtaPageCtrl);
                //Session["dsePageInputInfo"] = dsePageInputInfo;
            }
            //else if ((strPagesetRowID == "ps_pageset") || (strPagesetRowID == "ps_pgs_mem") || (strPagesetRowID == "ps_pgs_srh"))
            else if ((strPagesetRowID == "b3ef063b174e4ccc") || (strPagesetRowID == "a40f400c6424ef4e") || (strPagesetRowID == "be2f0230028f06a6"))
            {
                if (dsePagesetInputInfo.Tables.Contains(dtaPage.Rows[0]["page_id"].ToString()) == false)
                    SR.CreatePageDataTable(dsePagesetInputInfo, dtaPage, dtaPageCtrl);
                GetDataset(dsePagesetInputInfo, strPagesetRowID, dtaPage, dtaPageCtrl);
                //Session["dsePagesetInputInfo"] = dsePagesetInputInfo;
            }
        }
        return Status;
    }

    private void GetDataset(DataSet dseObj, string strPagesetRowID, DataTable dtaPage, DataTable dtaPageCtrl)
    {
        string strPageId;
        DataRow droPageData;
        HDD = new HDDatabase();
        ScreenReader SR = new ScreenReader();

        switch (strPagesetRowID.ToLower())
        {
            case "9ec6aa32504a516b": // ps_dobj
            case "cdb0ecf826945479": // ps_dobj_att

                for (int i = 0; i < dtaPage.Rows.Count; i++)
                {
                    strPageId = dtaPage.Rows[i]["page_id"].ToString();
                    dseObj.Tables[strPageId].Clear();

                    if (strPageId == "p_dobj")
                    {
                        droPageData = dseObj.Tables[strPageId].NewRow();
                        droPageData["object_id"] = obj_id.Value;
                        droPageData["object_name"] = GenerateName(txt_page_name.Text);
                        droPageData["object_table"] = obj_bu_id.Value;
                        droPageData["af_row_id"] = obj_rowkey.Value;
                        droPageData["associate_notes"] = cb_associate_notes.Checked; 
                        droPageData["associate_documents"] = cb_associate_documents.Checked; 
                        droPageData["associate_task"] = cb_associate_task.Checked; 

                        if (dseObj.Tables[strPageId].Columns.Contains("owner_id"))
                            droPageData["owner_id"] = page_owner_id.Value;

                        dseObj.Tables[strPageId].Rows.Add(droPageData);
                    }
                    else if (strPageId == "p_dobj_att")
                    {
                        dseObj.Tables[strPageId].Clear();
                        int k = 0;
                        foreach (DataRow drObjAtt in dt_controldetails.Rows)
                        {
                            k = k + 1;
                            droPageData = dseObj.Tables[strPageId].NewRow();
                            droPageData["object_id"] = obj_rowkey.Value;
                            droPageData["af_row_id"] = drObjAtt["obj_att_row_id"].ToString();// == "" ? SR.getHashKey() : drObjAtt["obj_att_row_id"].ToString();
                            droPageData["attrib_id"] = drObjAtt["txt_control_id"].ToString();
                            droPageData["attrib_name"] = drObjAtt["txt_name"].ToString();
                            droPageData["attrib_description"] = drObjAtt["txt_desc"].ToString();
                            droPageData["object_tooltip"] = drObjAtt["txt_tooltip"].ToString();
                            droPageData["attrib_data_type"] = drObjAtt["ddl_data_type"].ToString();
                            droPageData["attrib_seq"] = k;
                            droPageData["is_primary"] = drObjAtt["ddl_is_unique"].ToString();
                            bool isEmail = drObjAtt["ddl_ctr_type"].ToString().ToUpper() == "EM";
                            droPageData["attrib_size"] = (!isEmail ? drObjAtt["txt_size"].ToString() : (drObjAtt["txt_size"].ToString() == "" ? "255" : (Convert.ToInt32(drObjAtt["txt_size"].ToString()) < 255 ? "255" : drObjAtt["txt_size"].ToString())));
                            droPageData["field_type"] = drObjAtt["ddl_field_type"].ToString();

                            if (dseObj.Tables[strPageId].Columns.Contains("owner_id"))
                                droPageData["owner_id"] = drObjAtt["ctr_owner"].ToString() == "" ? Session["user_afrowid"].ToString() : drObjAtt["ctr_owner"].ToString();

                            dseObj.Tables[strPageId].Rows.Add(droPageData);
                        }
                    }
                }
                break;

            case "50f21749fc3da2ee": // ps_page
            case "534b6e11207db844": // ps_pg_ctr
            case "3b58ce68486728f4": // pg_ctr_droplist

                for (int i = 0; i < dtaPage.Rows.Count; i++)
                {
                    strPageId = dtaPage.Rows[i]["page_id"].ToString();
                    dseObj.Tables[strPageId].Clear();
                    if (strPageId == "p_pg")
                    {
                        droPageData = dseObj.Tables[strPageId].NewRow();
                        if (droPageData.Table.Columns.Contains("page_desc"))
                            droPageData["page_desc"] = txt_page_desc.Text;
                        droPageData["page_id"] = pg_id.Value;
                        droPageData["page_name"] = txt_page_name.Text;
                        droPageData["page_table_name"] = obj_bu_id.Value;
                        droPageData["object_id"] = obj_id.Value;
                        droPageData["af_row_id"] = pg_rowkey.Value;
                        droPageData["page_view"] = ddl_template.SelectedValue;
                        droPageData["page_icon"] = ddl_icon.SelectedValue;
                        droPageData["sections_as_tabs"] = cb_section_as_tabs.Checked;
                        droPageData["multiple_recs_page"] = cb_multiple_record.Checked;
                        droPageData["control_per_row"] = txt_controls_per_row.Text;
                        droPageData["first_row_caption_only"] = cb_caption_row.Checked;

                        if (dtaPage.Columns.Contains("modified_date"))
                            droPageData["modified_date"] = System.DateTime.Now;
                        else if (dtaPage.Columns.Contains("modified_at"))
                            droPageData["modified_at"] = System.DateTime.Now;

                        if (dtaPage.Columns.Contains("created_date"))
                            droPageData["created_date"] = System.DateTime.Now;
                        else if (dtaPage.Columns.Contains("created_at"))
                            droPageData["created_at"] = System.DateTime.Now;

                        if (dseObj.Tables[strPageId].Columns.Contains("owner_id"))
                            droPageData["owner_id"] = page_owner_id.Value;

                        dseObj.Tables[strPageId].Rows.Add(droPageData);
                    }
                    else if (strPageId == "p_pg_ctr")
                    {
                        foreach (DataRow drPgCtr in dt_controldetails.Rows)
                        {
                            droPageData = dseObj.Tables[strPageId].NewRow();
                            droPageData["control_seq"] = drPgCtr["txt_seq"].ToString();
                            droPageData["page_id"] = pg_rowkey.Value;
                            droPageData["af_row_id"] = drPgCtr["pg_ctr_row_id"].ToString() == "" ? SR.getHashKey() : drPgCtr["pg_ctr_row_id"].ToString();
                            drPgCtr["pg_ctr_row_id"] = droPageData["af_row_id"].ToString();
                            droPageData["control_id"] = drPgCtr["txt_control_id"].ToString();
                            droPageData["control_name"] = drPgCtr["txt_name"].ToString();
                            droPageData["control_html"] = drPgCtr["ddl_ctr_type"].ToString();
                            droPageData["control_attrib_id"] = drPgCtr["txt_control_id"].ToString();
                            droPageData["control_attrib_type"] = drPgCtr["ddl_data_type"].ToString();
                            droPageData["control_bind_id"] = drPgCtr["ddl_data_bind"].ToString();
                            droPageData["input_mask_format"] = drPgCtr["ddl_format_mask"].ToString();
                            droPageData["control_visible"] = drPgCtr["ddl_visible"].ToString();
                            droPageData["read_only"] = drPgCtr["ddl_is_read"].ToString();
                            droPageData["is_section"] = drPgCtr["ddl_new_section"].ToString();
                            droPageData["section_name"] = drPgCtr["txt_section_name"].ToString();
                            droPageData["is_search"] = drPgCtr["ddl_search"].ToString();
                            droPageData["default_value"] = drPgCtr["txt_default_value"].ToString();

                            if (dseObj.Tables[strPageId].Columns.Contains("owner_id"))
                                droPageData["owner_id"] = drPgCtr["ctr_owner"].ToString() == "" ? Session["user_afrowid"].ToString() : drPgCtr["ctr_owner"].ToString();

                            dseObj.Tables[strPageId].Rows.Add(droPageData);
                        }

                        if (IsEdit == false)
                        {
                            foreach (DataRow dr in dt_default_col.Rows)
                            {
                                droPageData = dseObj.Tables[strPageId].NewRow();
                                droPageData["control_seq"] = dseObj.Tables[strPageId].Rows.Count + 1000;
                                droPageData["page_id"] = pg_rowkey.Value;
                                droPageData["af_row_id"] = SR.getHashKey();
                                droPageData["control_id"] = dr["mem_id"].ToString();
                                droPageData["control_name"] = dr["mem_name"].ToString();
                                droPageData["control_html"] = "TB";
                                droPageData["control_attrib_id"] = dr["mem_id"].ToString();
                                droPageData["control_attrib_type"] = "TX";
                                droPageData["control_visible"] = "False";
                                droPageData["is_section"] = "False";
                                droPageData["is_search"] = "False";
                                droPageData["read_only"] = "False";

                                if (droPageData["control_id"].ToString().ToLower() == "owner_id")
                                {
                                    droPageData["control_visible"] = true;
                                    droPageData["control_html"] = "TB";
                                    droPageData["control_bind_id"] = dr["mem_value3"].ToString().Trim();
                                }

                                if (dseObj.Tables[strPageId].Columns.Contains("owner_id"))
                                    droPageData["owner_id"] = page_owner_id.Value;

                                dseObj.Tables[strPageId].Rows.Add(droPageData);
                            }
                        }
                    }
                    else if (strPageId == "p_pg_ctr_droplist") // Added by 'Imran Gani' on 26-Dec-2013, for droplist values.
                    {
                        foreach (DataRow drPgCtr in dt_controldetails.Rows)
                        {
                            string sVal = drPgCtr["ta_droplist"].ToString();
                            if (sVal.Contains("\n"))
                            {
                                int seq = 0;
                                sVal = sVal.Replace("\r\n", "|").Replace("\n", "|");
                                foreach (string st in sVal.Split('|'))
                                {
                                    if (st == "") continue;
                                    if (dseObj.Tables[strPageId].Select("droplist_value = '" + st.Replace("'", "''") + "'").Length > 0) continue;
                                    droPageData = dseObj.Tables[strPageId].NewRow();
                                    droPageData["page_id"] = pg_rowkey.Value;
                                    droPageData["control_id"] = drPgCtr["pg_ctr_row_id"].ToString();
                                    droPageData["droplist_value"] = st;
                                    droPageData["droplist_seq"] = seq++;
                                    droPageData["owner_id"] = drPgCtr["ctr_owner"].ToString() == "" ? Session["user_afrowid"].ToString() : drPgCtr["ctr_owner"].ToString();
                                    dseObj.Tables[strPageId].Rows.Add(droPageData);
                                }
                            }
                            else if (sVal != "")
                            {
                                droPageData = dseObj.Tables[strPageId].NewRow();
                                droPageData["droplist_seq"] = 0;
                                droPageData["droplist_value"] = sVal;
                                droPageData["page_id"] = pg_rowkey.Value;
                                droPageData["control_id"] = drPgCtr["pg_ctr_row_id"].ToString();
                                droPageData["owner_id"] = drPgCtr["ctr_owner"].ToString() == "" ? Session["user_afrowid"].ToString() : drPgCtr["ctr_owner"].ToString();
                                dseObj.Tables[strPageId].Rows.Add(droPageData);
                            }
                        }
                    }
                }
                break;

            case "b3ef063b174e4ccc": // ps_pageset
            case "a40f400c6424ef4e": // ps_pgs_mem
            case "be2f0230028f06a6": // ps_pgs_srh

                for (int i = 0; i < dtaPage.Rows.Count; i++)
                {
                    strPageId = dtaPage.Rows[i]["page_id"].ToString();
                    dseObj.Tables[strPageId].Clear();

                    if (strPageId == "p_pgs")
                    {
                        droPageData = dseObj.Tables[strPageId].NewRow();
                        droPageData["pageset_id"] = ps_id.Value;
                        droPageData["pageset_name"] = txt_page_name.Text;
                        droPageData["Pageset_template"] = ddl_template.Text;
                        droPageData["af_row_id"] = ps_rowkey.Value;

                        if (dseObj.Tables[strPageId].Columns.Contains("owner_id"))
                            droPageData["owner_id"] = page_owner_id.Value;

                        dseObj.Tables[strPageId].Rows.Add(droPageData);
                    }
                    else if (strPageId == "p_pgs_mem")
                    {
                        droPageData = dseObj.Tables[strPageId].NewRow();
                        droPageData["pageset_id"] = ps_rowkey.Value;
                        droPageData["page_id"] = pg_id.Value;
                        droPageData["page_seq"] = 1;
                        droPageData["page_name"] = txt_page_name.Text;
                        droPageData["object_id"] = obj_id.Value;
                        droPageData["is_master"] = "True";
                        droPageData["af_row_id"] = SR.getHashKey();

                        if (dseObj.Tables[strPageId].Columns.Contains("owner_id"))
                            droPageData["owner_id"] = page_owner_id.Value;

                        dseObj.Tables[strPageId].Rows.Add(droPageData);
                    }
                    else if (strPageId == "p_pgs_srh")
                    {
                        int l = 0;
                        foreach (DataRow drSrh in dt_controldetails.Rows)
                        {
                            if (drSrh["ddl_in_list"].ToString().ToLower() == "true" || drSrh["ddl_filter"].ToString().ToLower() == "true")
                            {
                                l = l + 1;
                                droPageData = dseObj.Tables[strPageId].NewRow();
                                droPageData["pageset_id"] = ps_rowkey.Value;
                                droPageData["search_seq"] = (drSrh["txt_seq"].ToString() == "" ? l.ToString() : drSrh["txt_seq"].ToString());
                                droPageData["page_id"] = pg_id.Value;
                                droPageData["search_attrib_id"] = drSrh["txt_control_id"].ToString();
                                droPageData["search_attrib_name"] = drSrh["txt_name"].ToString();
                                droPageData["list_flag"] = drSrh["ddl_in_list"].ToString();
                                droPageData["quick_search"] = drSrh["ddl_filter"].ToString();
                                droPageData["af_row_id"] = SR.getHashKey();

                                if (dseObj.Tables[strPageId].Columns.Contains("owner_id"))
                                    droPageData["owner_id"] = page_owner_id.Value;

                                dseObj.Tables[strPageId].Rows.Add(droPageData);
                            }
                        }
                    }
                }
                break;
        }
    }

    private void ModifyDataSets()
    {
        HDD = new HDDatabase();
        DataTable dt_obj_att_old;

        if (IsEdit && !IsCopy)
        {
            dt_obj_att_old = HDD.GetDataTable("Select * from sy_pgs_mem where pageset_id ='" + ps_rowkey.Value + "'");
            foreach (DataRow dr in dsePagesetInputInfo.Tables["p_pgs_mem"].Rows)
            {
                DataRow[] drr = dt_obj_att_old.Select("page_id = '" + dr["page_id"].ToString().Replace("'", "''") + "'");
                if (drr.Length > 0)
                    dr["af_row_id"] = drr[0]["af_row_id"];
            }

            dt_obj_att_old = HDD.GetDataTable("Select * from sy_pgs_srh where pageset_id ='" + ps_rowkey.Value + "'");
            foreach (DataRow dr in dsePagesetInputInfo.Tables["p_pgs_srh"].Rows)
            {
                string seq = dr["search_seq"].ToString();
                if (seq.Trim() == "")
                    seq = " ";
                DataRow[] drr = dt_obj_att_old.Select("page_id = '" + dr["page_id"].ToString().Replace("'", "''") + "' and search_seq = '" + seq + "'");
                //DataRow[] drr = dt_obj_att_old.Select("page_id = '" + dr["page_id"].ToString().Replace("'", "''") + "' and search_seq = '" + dr["search_seq"] + "'");
                if (drr.Length > 0)
                    dr["af_row_id"] = drr[0]["af_row_id"];
            }
        }

        foreach (DataRow dr in dt_default_col.Rows)
        {
            DataRow[] drobj = dseObjectInputInfo.Tables["p_dobj_att"].Select("attrib_name = '" + dr["mem_name"].ToString() + "'");
            if (drobj.Length > 0)
                drobj[0]["attrib_id"] = dr["mem_id"].ToString();
            DataRow[] drpg = dsePageInputInfo.Tables["p_pg_ctr"].Select("control_name = '" + dr["mem_name"].ToString() + "'");
            if (drpg.Length > 0)
            {
                drpg[0]["control_id"] = dr["mem_id"].ToString();
                drpg[0]["control_attrib_id"] = dr["mem_id"].ToString();
            }
        }

        if (IsCopy)
        {
            for (int i = 0; i < defaultColumns.Count; i++)
            {
                if (dseObjectInputInfo.Tables["p_dobj_att"].Select("attrib_id = '" + defaultColumns[i].ToString().ToLower() + "'").Length > 0)
                    dseObjectInputInfo.Tables["p_dobj_att"].Rows.Remove(dseObjectInputInfo.Tables["p_dobj_att"].Select("attrib_id = '" + defaultColumns[i].ToString().ToLower() + "'")[0]);
            }
        }

        if (dseObjectInputInfo.Tables["p_dobj_att"].Select("is_primary = 'True'").Length > 1)
            dseObjectInputInfo.Tables["p_dobj"].Rows[0]["is_composite"] = true;
    }

    private void DefaultColumnUpdate()
    {
        string strPageId = "";
        string[,] pagearr = pagearr = new string[,] 
            {
                {"Object", "p_dobj"},
                {"Object", "p_dobj_att"}, 

                {"Page", "p_pg"},
                {"Page", "p_pg_ctr"},
                {"Page", "p_pg_ctr_droplist"}, // Added by 'Imran Gani' on 26-Dec-2013, for droplist values.

                {"Pageset", "p_pgs"},
                {"Pageset", "p_pgs_mem"},
                {"Pageset", "p_pgs_srh"}
            };

        for (int j = 0; j <= pagearr.GetUpperBound(0); j++)
        {
            strPageId = pagearr[j, 1].ToString();
            foreach (DataRow dr in dseInputInfo.Tables[strPageId].Rows)
            {
                if (dseInputInfo.Tables[strPageId].Columns.Contains("modified_date"))
                    dr["modified_date"] = DateTime.Now.ToString();
                else if (dseInputInfo.Tables[strPageId].Columns.Contains("modified_at"))
                    dr["modified_at"] = DateTime.Now.ToString();

                if (dseInputInfo.Tables[strPageId].Columns.Contains("created_date"))
                    dr["created_date"] = DateTime.Now.ToString();
                else if (dseInputInfo.Tables[strPageId].Columns.Contains("created_at"))
                    dr["created_at"] = DateTime.Now.ToString();

                if (dseInputInfo.Tables[strPageId].Columns.Contains("modified_by"))
                    dr["modified_by"] = HttpContext.Current.Session["user_afrowid"].ToString();

                if ((IsEdit) && (!IsCopy))
                {
                }
                else
                {
                    if (dseInputInfo.Tables[strPageId].Columns.Contains("created_by"))
                    {
                        dr["created_by"] = HttpContext.Current.Session["user_afrowid"].ToString();
                    }
                }
                if (dseInputInfo.Tables[strPageId].Columns.Contains("owner_id"))
                {
                    //dr["owner_id"] = owner_id.Value; // Commented By 'Imran Gani' on 23-Jul-2013, For owner of a page control
                }
            }
        }
    }

    private bool MergePageset(ref string message)
    {
        bool blnStatus = true;
        DataSet dsetempInfo;
        ScreenReader SR = new ScreenReader();
        string strPagesetRowID = "";
        string[,] pagearr = pagearr = new string[,] 
            {
                {"Object", "9ec6aa32504a516b"}, // ps_dobj
                {"Object", "cdb0ecf826945479"}, // ps_dobj_att

                {"Page", "50f21749fc3da2ee"}, // ps_page
                {"Page", "534b6e11207db844"}, // ps_pg_ctr
                {"Page", "3b58ce68486728f4"}, // pg_ctr_droplist // Added by 'Imran Gani' on 26-Dec-2013, for droplist values.

                {"Pageset", "b3ef063b174e4ccc"}, // ps_pageset
                {"Pageset", "a40f400c6424ef4e"}, // ps_pgs_mem
                {"Pageset", "be2f0230028f06a6"}, // ps_pgs_srh
            };
        PageInfoLoad PIL = new PageInfoLoad();
        dsePageInfo = new DataSet();
        dseInputInfo = new DataSet();

        //dsePageInfo = PIL.GetPageSetPageCtrlInfo("ps_dobj");
        dsePageInfo = PIL.GetPageSetPageCtrlInfo("9ec6aa32504a516b");

        for (int j = 1; j <= pagearr.GetUpperBound(0); j++)
        {
            dsetempInfo = new DataSet();
            strPagesetRowID = pagearr[j, 1].ToString();
            dsetempInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);
            dsePageInfo.Tables["Page"].Merge(dsetempInfo.Tables["Page"]);
            dsePageInfo.Tables["PageCtrl"].Merge(dsetempInfo.Tables["PageCtrl"]);
            dsePageInfo.Tables["PageKeys"].Merge(dsetempInfo.Tables["PageKeys"]);
        }

        dseInputInfo.Merge(dseObjectInputInfo, true);
        dseInputInfo.Merge(dsePageInputInfo, true);
        dseInputInfo.Merge(dsePagesetInputInfo, true);

        DefaultColumnUpdate();

        if (IsCopy)
        {
            foreach (DataTable dt in dseInputInfo.Tables)
            {
                if ((dt.TableName != "p_dobj") && (dt.TableName != "p_pg") && (dt.TableName != "p_pgs"))
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        dr["af_row_id"] = SR.getHashKey();
                    }
                }
            }
        }

        if (dseInputInfo.Tables["p_dobj_att"].Rows.Count > 0)
        {
            if (dseInputInfo.Tables["p_pgs_srh"].Rows.Count > 0)
            {
                if (dseInputInfo.Tables["p_pgs_srh"].Select("list_flag = True").Length > 0)
                {
                    string duplicateList = DuplicateRows(dseInputInfo.Tables["p_pg_ctr"], "control_id");

                    if (duplicateList.Trim().Length > 0)
                    {
                        blnStatus = false;
                        message = "The followings controls are duplicated - " + duplicateList;
                    }
                    else
                    {
                        blnStatus = InsertTableRows(dsePageInfo, dseInputInfo);
                    }
                }
                else
                {
                    blnStatus = false;
                    message = "Select a control for the List View. ";
                }
            }
            else
            {
                blnStatus = false;
                message = "Select a control for the List View. ";
            }
        }
        else
        {
            blnStatus = false;
            message = "Page should have at least a control. ";
        }
        return blnStatus;
    }

    public string DuplicateRows(DataTable dTable, string colName)
    {
        Hashtable hTable = new Hashtable();
        string duplicateList = "";

        foreach (DataRow drow in dTable.Rows)
        {
            if (hTable.ContainsKey(drow[colName]))
                duplicateList = duplicateList + drow[colName].ToString() + ",";
            else
                hTable.Add(drow[colName], string.Empty);
        }

        if (duplicateList.Trim().Length > 0)
            duplicateList = duplicateList.Substring(0, duplicateList.Length - 1);

        return duplicateList;
    }

    private bool InsertTableRows(DataSet dsePageInfo, DataSet dseInputInfo)
    {
        Master MA = new Master();
        bool blnStatus = true;
        try
        {
            if (IsEdit && !IsCopy)
            {
                if (updatePageDetails(dseInputInfo))
                    blnStatus = MA.generateTableAndPage(obj_id.Value, obj_rowkey.Value, false);
                else
                    blnStatus = false;
            }
            else
                blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");
        }
        catch (Exception ex)
        {
            blnStatus = false;
            LogWriter.WriteLog("Error : PageDesigner : InsertTableRows : " + ex.Message);
        }
        return blnStatus;
    }

    private bool updatePageDetails(DataSet dseInputInfo)
    {
        bool blnStatus = false;
        string updateSQL = string.Empty;
        string sDelRowId = string.Empty;
        ScreenReader sr = new ScreenReader();
        DataTable dt_exist = new DataTable();
        try
        {
            string sql_data = "select [pg_ctr].[af_row_id] as [pg_ctr_row_id], [obj_att].[af_row_id] as [obj_att_row_id], [pg_ctr].[owner_id] as [ctr_owner], " +
                                    "[pg_ctr].[control_name] as [txt_name], [obj_att].[attrib_description] as [txt_desc], [pg_ctr].[control_seq] as [txt_seq], [pg_ctr].[control_html] as [ddl_ctr_type], [pg_ctr].[control_attrib_type] as [ddl_data_type], " +
                                    "[pg_ctr].[control_id] as [txt_control_id], [pg_ctr].[control_visible] as [ddl_visible], [pg_ctr].[read_only] as [ddl_is_read], [srh].[list_flag] as [ddl_in_list], [obj_att].[attrib_size] as [txt_size], " +
                                    "[pg_ctr].[default_value] as [txt_default_value], [obj_att].[is_primary] as [ddl_is_unique], [srh].[quick_search] as [ddl_filter], [obj_att].[object_tooltip] as [txt_tooltip], [pg_ctr].[control_bind_id] as [ddl_data_bind], " +
                                    "[pg_ctr].[input_mask_format] as [ddl_format_mask], [pg_ctr].[is_section] as [ddl_new_section], [pg_ctr].[is_search] as [ddl_search], [pg_ctr].[section_name] as [txt_section_name], [obj_att].[field_type] as [ddl_field_type] " +
                                    "from [sy_pg_ctr] [pg_ctr] " +
                                    "inner join [sy_pg] [pg] on [pg].[af_row_id] = [pg_ctr].[page_id] " +
                                    "inner join [sy_pgs_mem] [mem] on [pg].[page_id] = [mem].[page_id] " +
                                    "inner join [sy_obj] [obj] on [obj].[object_id] = [mem].[object_id] " +
                                    "inner join [sy_obj_att] [obj_att] on [obj].[af_row_id] = [obj_att].[object_id] and [obj_att].[attrib_id] = [pg_ctr].[control_id] " +
                                    "left join [sy_pgs_srh] [srh] on [srh].[pageset_id] = [mem].[pageset_id] and [srh].[search_attrib_id] = [pg_ctr].[control_id] " +
                                    "where [mem].[pageset_id] = '" + Request.QueryString["PK"].ToString() + "' " +
                                    "and [pg_ctr].[control_id] not in ('created_by','created_at','modified_at','modified_by','owner_id','af_row_id') " +
                                    "and [obj_att].[attrib_id] not in ('created_by','created_at','modified_at','modified_by','owner_id','af_row_id');";
            dt_exist = HDD.GetDataTable(sql_data);
            foreach (DataTable dt in dseInputInfo.Tables)
            {
                switch (dt.TableName)
                {

                    case "p_dobj":
                        updateSQL += "UPDATE [sy_obj] SET [object_id] = '" + dt.Rows[0]["object_id"].ToString() + "',[object_name] = '" + dt.Rows[0]["object_name"].ToString() + "',[object_table] = '" + dt.Rows[0]["object_table"].ToString() + "',[associate_notes] = '" + dt.Rows[0]["associate_notes"].ToString() + "',[associate_documents] = '" + dt.Rows[0]["associate_documents"].ToString() + "',[associate_task] = '" + dt.Rows[0]["associate_task"].ToString() + "',[modified_at] = '" + dt.Rows[0]["modified_at"].ToString() + "',[modified_by] = '" + dt.Rows[0]["modified_by"].ToString() + "',[owner_id] = '" + dt.Rows[0]["owner_id"].ToString() + "' WHERE [af_row_id] = '" + dt.Rows[0]["af_row_id"].ToString() + "';";
                        break;
                    case "p_dobj_att":
                        string sExistRow = string.Empty;
                        sDelRowId = string.Empty;
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (dr["af_row_id"].ToString() != "")
                            {
                                updateSQL += "UPDATE [sy_obj_att] SET [object_id] = '" + dr["object_id"].ToString() + "',[attrib_id] = '" + dr["attrib_id"].ToString() + "',[attrib_name] = '" + dr["attrib_name"].ToString() + "',[attrib_seq] = '" + dr["attrib_seq"].ToString() + "',[attrib_size] = " + (dr["attrib_size"].ToString() == "" ? "null" : dr["attrib_size"].ToString()) + ",[attrib_data_type] = '" + dr["attrib_data_type"].ToString() + "',[attrib_description] = " + (dr["attrib_description"].ToString() == "" ? "null" : "'" + dr["attrib_description"].ToString() + "'") + ",[object_tooltip] = " + (dr["object_tooltip"].ToString() == "" ? "null" : "'" + dr["object_tooltip"].ToString() + "'") + ",[is_primary] = '" + dr["is_primary"].ToString() + "',[field_type] = '" + dr["field_type"].ToString() + "',[modified_at] = '" + dr["modified_at"].ToString() + "',[modified_by] = '" + dr["modified_by"].ToString() + "',[owner_id] = '" + dr["owner_id"].ToString() + "' WHERE [af_row_id] = '" + dr["af_row_id"].ToString() + "';";
                                sExistRow += "'" + dr["af_row_id"].ToString() + "',";
                            }
                            else
                            {
                                updateSQL += "INSERT INTO [sy_obj_att] ([af_row_id],[object_id],[attrib_id],[attrib_seq],[attrib_name],[attrib_size],[attrib_data_type],[attrib_description],[object_tooltip],[is_primary],[created_by],[created_at],[modified_at],[modified_by],[owner_id],[field_type])" +
                                    "VALUES ('" + sr.getHashKey() + "','" + dr["object_id"].ToString() + "','" + dr["attrib_id"].ToString() + "','" + dr["attrib_seq"].ToString() + "','" + dr["attrib_name"].ToString() + "'," + (dr["attrib_size"].ToString() == "" ? "null" : dr["attrib_size"].ToString()) + ",'" + dr["attrib_data_type"].ToString() + "'," + (dr["attrib_description"].ToString() == "" ? "null" : "'" + dr["attrib_description"].ToString() + "'") + "," + (dr["object_tooltip"].ToString() == "" ? "null" : "'" + dr["object_tooltip"].ToString() + "'") + ",'" + dr["is_primary"].ToString() + "','" + dr["created_by"].ToString() + "','" + dr["created_at"].ToString() + "','" + dr["modified_at"].ToString() + "','" + dr["modified_by"].ToString() + "','" + dr["owner_id"].ToString() + "','" + dr["field_type"].ToString() + "');";
                            }
                        }
                        foreach (DataRow drDel in dt_exist.Select("obj_att_row_id not in (" + sExistRow.TrimEnd(',') + ")"))
                        {
                            sDelRowId += "'" + drDel["obj_att_row_id"].ToString() + "',";
                        }
                        if (sDelRowId != "")
                            updateSQL += "DELETE FROM [sy_obj_att] WHERE [af_row_id] in (" + sDelRowId.TrimEnd(',') + ");";
                        break;
                    case "p_pg":
                        updateSQL += "UPDATE [sy_pg] SET [page_id] = '" + dt.Rows[0]["page_id"].ToString() + "',[page_name] = '" + dt.Rows[0]["page_name"].ToString() + "',[page_table_name] = '" + dt.Rows[0]["page_table_name"].ToString() + "',[object_id] = '" + dt.Rows[0]["object_id"].ToString() + "',[multiple_recs_page] = '" + dt.Rows[0]["multiple_recs_page"].ToString() + "',[page_view] = '" + dt.Rows[0]["page_view"].ToString() + "',[control_per_row] = " + (dt.Rows[0]["control_per_row"].ToString() == "" ? "null" : dt.Rows[0]["control_per_row"].ToString()) + ",[first_row_caption_only] = '" + dt.Rows[0]["first_row_caption_only"].ToString() + "',[modified_at] = '" + dt.Rows[0]["modified_at"].ToString() + "',[modified_by] = '" + dt.Rows[0]["modified_by"].ToString() + "',[page_desc] = " + (dt.Rows[0]["page_desc"].ToString() == "" ? "null" : "'" + dt.Rows[0]["page_desc"].ToString() + "'") + ",[page_icon] = '" + dt.Rows[0]["page_icon"].ToString() + "',[owner_id] = '" + dt.Rows[0]["owner_id"].ToString() + "',[sections_as_tabs] = '" + dt.Rows[0]["sections_as_tabs"].ToString() + "' WHERE [af_row_id] = '" + dt.Rows[0]["af_row_id"].ToString() + "';";
                        break;
                    case "p_pg_ctr":
                        sExistRow = string.Empty;
                        sDelRowId = string.Empty;
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (dr["af_row_id"].ToString() != "" && dt_exist.Select("pg_ctr_row_id in ('" + dr["af_row_id"].ToString() + "')").Length > 0)
                            {
                                updateSQL += "UPDATE [sy_pg_ctr] SET [page_id] = '" + dr["page_id"].ToString() + "',[control_id] = '" + dr["control_id"].ToString() + "',[control_seq] = " + (dr["control_seq"].ToString() == "" ? "null" : dr["control_seq"].ToString()) + ",[control_name] = '" + dr["control_name"].ToString() + "',[control_html] = '" + dr["control_html"].ToString() + "',[control_attrib_id] = '" + dr["control_attrib_id"].ToString() + "',[control_attrib_type] = '" + dr["control_attrib_type"].ToString() + "',[control_bind_id] = " + (dr["control_bind_id"].ToString() == "" ? "null" : "'" + dr["control_bind_id"].ToString() + "'") + " ,[control_visible] = '" + dr["control_visible"].ToString() + "',[default_value] = " + (dr["default_value"].ToString() == "" ? "null" : "'" + dr["default_value"].ToString() + "'") + ",[read_only] = '" + dr["read_only"].ToString() + "',[modified_at] = '" + dr["modified_at"].ToString() + "',[modified_by] = '" + dr["modified_by"].ToString() + "',[input_mask_format] = " + (dr["input_mask_format"].ToString() == "" ? "null" : "'" + dr["input_mask_format"].ToString() + "'") + ",[is_section] = '" + dr["is_section"].ToString() + "',[owner_id] = '" + dr["owner_id"].ToString() + "',[section_name] = " + (dr["section_name"].ToString() == "" ? "null" : "'" + dr["section_name"].ToString() + "'") + ",[is_search] = '" + dr["is_search"].ToString() + "' WHERE [af_row_id] = '" + dr["af_row_id"].ToString() + "';";
                                sExistRow += "'" + dr["af_row_id"].ToString() + "',";
                            }
                            else
                            {
                                updateSQL += "INSERT INTO [sy_pg_ctr] ([af_row_id],[page_id],[control_id],[control_seq],[control_name],[control_html],[control_attrib_id],[control_attrib_type],[control_bind_id],[control_visible],[default_value],[read_only],[created_by],[created_at],[modified_at],[modified_by],[input_mask_format],[is_section],[owner_id],[section_name],[is_search])" +
                                    "VALUES ('" + (dr["af_row_id"].ToString() == "" ? sr.getHashKey() : dr["af_row_id"].ToString()) + "','" + dr["page_id"].ToString() + "','" + dr["control_id"].ToString() + "'," + (dr["control_seq"].ToString() == "" ? "null" : dr["control_seq"].ToString()) + ",'" + dr["control_name"].ToString() + "','" + dr["control_html"].ToString() + "','" + dr["control_attrib_id"].ToString() + "','" + dr["control_attrib_type"].ToString() + "'," + (dr["control_bind_id"].ToString() == "" ? "null" : "'" + dr["control_bind_id"].ToString() + "'") + ",'" + dr["control_visible"].ToString() + "'," + (dr["default_value"].ToString() == "" ? "null" : "'" + dr["default_value"].ToString() + "'") + ",'" + dr["read_only"].ToString() + "','" + dr["created_by"].ToString() + "','" + dr["created_at"].ToString() + "','" + dr["modified_at"].ToString() + "','" + dr["modified_by"].ToString() + "'," + (dr["input_mask_format"].ToString() == "" ? "null" : "'" + dr["input_mask_format"].ToString() + "'") + ",'" + dr["is_section"].ToString() + "','" + dr["owner_id"].ToString() + "'," + (dr["section_name"].ToString() == "" ? "null" : "'" + dr["section_name"].ToString() + "'") + ",'" + dr["is_search"].ToString() + "');";
                            }
                        }
                        foreach (DataRow drDel in dt_exist.Select("pg_ctr_row_id not in (" + sExistRow.TrimEnd(',') + ")"))
                        {
                            sDelRowId += "'" + drDel["pg_ctr_row_id"].ToString() + "',";
                        }
                        if (sDelRowId != "")
                            updateSQL += "DELETE FROM [sy_pg_ctr] WHERE [af_row_id] in (" + sDelRowId.TrimEnd(',') + ");";
                        break;
                    case "p_pg_ctr_droplist": // Added by 'Imran Gani' on 26-Dec-2013, for droplist values.
                        updateSQL += "Delete from [sy_pg_ctr_droplist] where page_id= '" + pg_rowkey.Value + "'; ";

                        DataTable dt_ExistsDroplist = new DataTable();
                        if (dt.Rows.Count != 0)
                        {
                            string sFldRowId = "", sFieldName = "", sExistingVals = string.Empty;
                            dt_ExistsDroplist = HDD.GetDataTable("select * from [sy_pg_ctr_droplist] where page_id='" + dt.Rows[0]["page_id"].ToString() + "'");
                            foreach (DataRow dr in dt_ExistsDroplist.Rows)
                                sExistingVals += "'" + dr["droplist_value"].ToString().Replace("'", "''") + "',";
                            string strTableName = HDD.GetColumnValue("select [page_table_name] from [sy_pg] where [af_row_id] = '" + dt.Rows[0]["page_id"].ToString() + "';");
                            if (!string.IsNullOrEmpty(sExistingVals))
                            {
                                foreach (DataRow dr_new in dt.Select("droplist_value not in (" + sExistingVals.TrimEnd(',') + ")"))
                                {
                                    if (dr_new["droplist_value"].ToString().ToLower() == "none" || dr_new["droplist_value"].ToString().ToLower() == "empty") continue;
                                    DataRow[] dr_exits = dt_ExistsDroplist.Select("control_id = '" + dr_new["control_id"].ToString() + "' and droplist_seq = '" + dr_new["droplist_seq"].ToString() + "'");
                                    if (dr_exits.Length == 0) continue;
                                    //if (dr_new["droplist_value"].ToString() == dr_exits[0]["droplist_value"].ToString()) continue;
                                    if (sFldRowId != dr_new["control_id"].ToString())
                                    {
                                        sFieldName = HDD.GetColumnValue("select [control_id] from [sy_pg_ctr] where [af_row_id] = '" + dr_new["control_id"].ToString() + "';");
                                        sFldRowId = dr_new["control_id"].ToString();
                                    }
                                    updateSQL += "update [" + strTableName + "] set [" + sFieldName + "] = '" + dr_new["droplist_value"].ToString().Replace("'", "''") + "' where [" + sFieldName + "] = '" + dr_exits[0]["droplist_value"].ToString().Replace("'", "''") + "'; ";
                                }
                            }
                            foreach (DataRow dr_new in dt.Rows)
                                updateSQL += "INSERT INTO [sy_pg_ctr_droplist] ([page_id],[control_id],[droplist_seq],[droplist_value],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id]) VALUES ('" + dr_new["page_id"].ToString() + "','" + dr_new["control_id"].ToString() + "','" + dr_new["droplist_seq"].ToString() + "','" + dr_new["droplist_value"].ToString().Replace("'", "''") + "','" + sr.getHashKey() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + dr_new["created_at"].ToString() + "','" + dr_new["modified_at"].ToString() + "','" + dr_new["modified_by"].ToString() + "','" + dr_new["owner_id"].ToString() + "');";
                        }
                        break;

                    case "p_pgs":
                        updateSQL += "UPDATE [sy_pgs] SET [pageset_id] = '" + dt.Rows[0]["pageset_id"].ToString() + "',[pageset_name] = '" + dt.Rows[0]["pageset_name"].ToString() + "',[pageset_template] = '" + dt.Rows[0]["pageset_template"].ToString() + "',[modified_at] = '" + dt.Rows[0]["modified_at"].ToString() + "',[modified_by] ='" + dt.Rows[0]["modified_by"].ToString() + "',[owner_id] = '" + dt.Rows[0]["owner_id"].ToString() + "' WHERE [af_row_id] = '" + dt.Rows[0]["af_row_id"].ToString() + "';";
                        break;
                    case "p_pgs_mem":
                        SqlCommand sqlDelMem = new SqlCommand("DELETE FROM [sy_pgs_mem] WHERE [pageset_id] = '" + dt.Rows[0]["pageset_id"].ToString() + "'");
                        HDD.ExecuteCmdObj(sqlDelMem, true);
                        updateSQL += "INSERT INTO [sy_pgs_mem] ([af_row_id],[pageset_id],[page_id],[page_seq],[page_name],[object_id],[is_master],[created_by],[created_at],[modified_at],[modified_by],[owner_id])" +
                                        "VALUES ('" + dt.Rows[0]["af_row_id"].ToString() + "','" + dt.Rows[0]["pageset_id"].ToString() + "','" + dt.Rows[0]["page_id"].ToString() + "','" + dt.Rows[0]["page_seq"].ToString() + "','" + dt.Rows[0]["page_name"].ToString() + "','" + dt.Rows[0]["object_id"].ToString() + "','" + dt.Rows[0]["is_master"].ToString() + "','" + dt.Rows[0]["owner_id"].ToString() + "','" + dt.Rows[0]["created_at"].ToString() + "','" + dt.Rows[0]["modified_at"].ToString() + "','" + dt.Rows[0]["modified_by"].ToString() + "','" + dt.Rows[0]["owner_id"].ToString() + "');";
                        break;
                    case "p_pgs_srh":
                        SqlCommand sqlDelSrh = new SqlCommand("DELETE FROM [sy_pgs_srh] WHERE [pageset_id] = '" + dt.Rows[0]["pageset_id"].ToString() + "'");
                        HDD.ExecuteCmdObj(sqlDelSrh, true);
                        foreach (DataRow dr in dt.Rows)
                        {
                            updateSQL += "INSERT INTO [sy_pgs_srh] ([af_row_id],[pageset_id],[search_seq],[page_id],[search_attrib_id],[search_attrib_name],[list_flag],[quick_search],[created_by],[created_at],[modified_at],[modified_by],[owner_id])" +
                                            "VALUES ('" + dr["af_row_id"].ToString() + "','" + dr["pageset_id"].ToString() + "','" + dr["search_seq"].ToString() + "','" + dr["page_id"].ToString() + "','" + dr["search_attrib_id"].ToString() + "','" + dr["search_attrib_name"].ToString() + "','" + dr["list_flag"].ToString() + "','" + dr["quick_search"].ToString() + "','" + dr["owner_id"].ToString() + "','" + dr["created_at"].ToString() + "','" + dr["modified_at"].ToString() + "','" + dr["modified_by"].ToString() + "','" + dr["owner_id"].ToString() + "');";
                        }
                        break;
                }
            }
            SqlCommand sql = new SqlCommand(updateSQL);
            if (HDD.ExecuteCmdObj(sql, true) > 0)
                blnStatus = true;

            if (blnStatus)
            {
                DataTable dt_IsUnique = new DataTable();
                dt_IsUnique = HDD.GetDataTable("select [is_primary] from [sy_obj_att] where [object_id] = '" + obj_rowkey.Value + "' and [is_primary] = 1");
                if (dt_IsUnique.Rows.Count > 1)
                {
                    sql = new SqlCommand("UPDATE [sy_obj] SET [is_composite] = 1 WHERE [af_row_id] = '" + obj_rowkey.Value + "';");
                    HDD.ExecuteCmdObj(sql, true);
                }
                else
                {
                    sql = new SqlCommand("UPDATE [sy_obj] SET [is_composite] = null WHERE [af_row_id] = '" + obj_rowkey.Value + "';");
                    HDD.ExecuteCmdObj(sql, true);
                }
            }
        }
        catch (Exception ex)
        {
            blnStatus = false;
            LogWriter.WriteLog("Error : PageDesigner : updatePageDetails : " + ex.Message);
        }
        return blnStatus;
    }

    private void getRoleSecurity(string strMenuRowId)
    {
        ScreenReader sr = new ScreenReader();
        DataTable dtTemp = new DataTable();
        StringBuilder sbQuery = new StringBuilder();
        try
        {
            if (dt_RoleDetails != null)
            {
                foreach (DataRow dr in dt_RoleDetails.Rows)
                {
                    CheckBox chkBox_read = (CheckBox)frmObj.FindControl("ContentPlaceHolder3").FindControl("chk_read_" + dr["rol_af_row_id"].ToString());
                    if (chkBox_read != null && chkBox_read.Checked && dr["read"].ToString() != "True")
                        dr["read"] = true;
                    else if (chkBox_read != null && !chkBox_read.Checked && dr["read"].ToString() != "False" && dr["read"].ToString() != "")
                        dr["read"] = false;
                    CheckBox chkBox_create = (CheckBox)frmObj.FindControl("ContentPlaceHolder3").FindControl("chk_create_" + dr["rol_af_row_id"].ToString());
                    if (chkBox_create != null && chkBox_create.Checked && dr["create"].ToString() != "True")
                        dr["create"] = true;
                    else if (chkBox_create != null && !chkBox_create.Checked && dr["create"].ToString() != "False" && dr["create"].ToString() != "")
                        dr["create"] = false;
                    CheckBox chkBox_edit = (CheckBox)frmObj.FindControl("ContentPlaceHolder3").FindControl("chk_edit_" + dr["rol_af_row_id"].ToString());
                    if (chkBox_edit != null && chkBox_edit.Checked && dr["edit"].ToString() != "True")
                        dr["edit"] = true;
                    else if (chkBox_edit != null && !chkBox_edit.Checked && dr["edit"].ToString() != "False" && dr["edit"].ToString() != "")
                        dr["edit"] = false;
                    CheckBox chkBox_delete = (CheckBox)frmObj.FindControl("ContentPlaceHolder3").FindControl("chk_delete_" + dr["rol_af_row_id"].ToString());
                    if (chkBox_delete != null && chkBox_delete.Checked && dr["delete"].ToString() != "True")
                        dr["delete"] = true;
                    else if (chkBox_delete != null && !chkBox_delete.Checked && dr["delete"].ToString() != "False" && dr["delete"].ToString() != "")
                        dr["delete"] = false;
                    CheckBox chkBox_change_owner = (CheckBox)frmObj.FindControl("ContentPlaceHolder3").FindControl("chk_change_owner_" + dr["rol_af_row_id"].ToString());
                    if (chkBox_change_owner != null && chkBox_change_owner.Checked && dr["change_owner"].ToString() != "True")
                        dr["change_owner"] = true;
                    else if (chkBox_change_owner != null && !chkBox_change_owner.Checked && dr["change_owner"].ToString() != "False" && dr["change_owner"].ToString() != "")
                        dr["change_owner"] = false;

                    if (dr["obj_acc_af_row_id"].ToString() != "" && IsEdit)
                    {
                        sbQuery.Append("UPDATE [sy_obj_acc] SET [read] = " + (dr["read"].ToString() == "True" ? "1" : "0") + ", [create] = " + (dr["create"].ToString() == "True" ? "1" : "0") + ", [edit] = " + (dr["edit"].ToString() == "True" ? "1" : "0") + ", [delete] = " + (dr["delete"].ToString() == "True" ? "1" : "0") + ", [change_owner] = " + (dr["change_owner"].ToString() == "True" ? "1" : "0") + ", [modified_at] = '" + System.DateTime.Now.ToUniversalTime().ToString() + "',[modified_by] = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "' WHERE [af_row_id] = '" + dr["obj_acc_af_row_id"].ToString() + "';");
                        if (strMenuRowId != "" && dr["read"].ToString() == "True")
                        {
                            string Is_accessible = HDD.GetColumnValue("select is_accessible from sy_rol_acc where menu_id = '" + strMenuRowId + "' and role_id = '" + dr["rol_af_row_id"].ToString() + "';");
                            if (Is_accessible == "")
                                sbQuery.Append("insert into sy_rol_acc(af_row_id, role_id, menu_id, is_accessible, created_by, created_at, modified_at, modified_by,owner_id) values('" + sr.getHashKey() + "','" + dr["rol_af_row_id"].ToString() + "','" + strMenuRowId + "',1,'" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"] + "');");
                            if (Is_accessible.ToLower() == "false")
                                sbQuery.Append("UPDATE [sy_rol_acc] SET [is_accessible] = 1, [modified_at] = '" + System.DateTime.Now.ToUniversalTime().ToString() + "',[modified_by] = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "' WHERE [menu_id]  = '" + strMenuRowId + "' and role_id = '" + dr["rol_af_row_id"].ToString() + "';");
                        }
                    }
                    else
                    {
                        sbQuery.Append("INSERT INTO [sy_obj_acc]([af_row_id],[role_id],[object_id],[read],[create],[edit],[delete],[change_owner],[created_by],[created_at],[modified_at],[modified_by],[owner_id])VALUES('" + sr.getHashKey() + "','" + dr["rol_af_row_id"].ToString() + "','" + obj_id.Value + "'," + (dr["read"].ToString() == "True" ? "1" : "0") + "," + (dr["create"].ToString() == "True" ? "1" : "0") + "," + (dr["edit"].ToString() == "True" ? "1" : "0") + "," + (dr["delete"].ToString() == "True" ? "1" : "0") + "," + (dr["change_owner"].ToString() == "True" ? "1" : "0") + ",'" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "');");
                        if (strMenuRowId != "" && dr["read"].ToString() == "True")
                            sbQuery.Append("insert into sy_rol_acc(af_row_id, role_id, menu_id, is_accessible, created_by, created_at, modified_at, modified_by,owner_id) values('" + sr.getHashKey() + "','" + dr["rol_af_row_id"].ToString() + "','" + strMenuRowId + "',1,'" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"] + "');");
                    }
                }

                //dtTemp = dt_RoleDetails.GetChanges();
                //if (dtTemp != null && dtTemp.Rows.Count > 0)
                //{
                //    foreach (DataRow dr in dtTemp.Rows)
                //    {
                //        if (dr["obj_acc_af_row_id"].ToString() != "" && IsEdit)
                //            sbQuery.Append("UPDATE [sy_obj_acc] SET [read] = " + (dr["read"].ToString() == "True" ? "1" : "0") + ", [create] = " + (dr["create"].ToString() == "True" ? "1" : "0") + ", [edit] = " + (dr["edit"].ToString() == "True" ? "1" : "0") + ", [delete] = " + (dr["delete"].ToString() == "True" ? "1" : "0") + ", [change_owner] = " + (dr["change_owner"].ToString() == "True" ? "1" : "0") + ", [modified_at] = '" + System.DateTime.Now.ToUniversalTime().ToString() + "',[modified_by] = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "' WHERE [af_row_id] = '" + dr["obj_acc_af_row_id"].ToString() + "';");
                //        else
                //        {
                //            sbQuery.Append("INSERT INTO [sy_obj_acc]([af_row_id],[role_id],[object_id],[read],[create],[edit],[delete],[change_owner],[created_by],[created_at],[modified_at],[modified_by],[owner_id])VALUES('" + sr.getHashKey() + "','" + dr["rol_af_row_id"].ToString() + "','" + obj_id.Value + "'," + (dr["read"].ToString() == "True" ? "1" : "0") + "," + (dr["create"].ToString() == "True" ? "1" : "0") + "," + (dr["edit"].ToString() == "True" ? "1" : "0") + "," + (dr["delete"].ToString() == "True" ? "1" : "0") + "," + (dr["change_owner"].ToString() == "True" ? "1" : "0") + ",'" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + System.DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "');");
                //            if (strMenuRowId != "")
                //                sbQuery.Append("insert into sy_rol_acc(af_row_id, role_id, menu_id, is_accessible, created_by, created_at, modified_at, modified_by,owner_id) values('" + sr.getHashKey() + "','" + dr["rol_af_row_id"].ToString() + "'," + strMenuRowId + ",1,'" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"] + "');");
                //        }
                //    }
                //}
                if (sbQuery.ToString() != "")
                {
                    SqlCommand sql = new SqlCommand(sbQuery.ToString());
                    HDD.ExecuteCmdObj(sql, true);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error: pagedesigner: getRoleSecurity() : " + ex.Message);
        }
        finally
        {
            if (dtTemp != null)
                dtTemp.Dispose();
            sbQuery.Clear();
        }
    }

    private string createMenuForPage()
    {
        string sMenuId = "", strMenuRowId = "";
        try
        {
            ScreenReader sr = new ScreenReader();
            string parent_menu_id = ddl_parent_menu.SelectedValue;
            strMenuRowId = sr.getHashKey();
            sMenuId = getAutoNumberValue("sy_mnu", "menu_id");
            string menu_sql = "insert into sy_mnu(af_row_id, menu_id, menu_name, parent_menu_id, pageset_id, " +
                                "pageset_url_type, menu_click, is_active, created_by, created_at, modified_at, modified_by,owner_id) " +
                                " values('" + strMenuRowId + "'," + sMenuId + ",'" + txt_page_name.Text.Replace("'", "''") + "','" + (parent_menu_id == "" ? "" : parent_menu_id) + "','" + ps_rowkey.Value + "'," +
                                "1,1,1,'" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" +
                                DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() +
                                "','" + HttpContext.Current.Session["user_afrowid"].ToString() + "','" + HttpContext.Current.Session["user_afrowid"] + "')";
            if (HDD.ExecuteCmdObj(new SqlCommand(menu_sql)) < 1)
                return "";
            sr = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in createMenuForPage. " + e.Message);
        }
        return strMenuRowId;
    }

    private void updateParentMenuID(string strMenuRowId)
    {
        try
        {
            ScreenReader sr = new ScreenReader();
            string parent_menu_id = ddl_parent_menu.SelectedValue;
            string menu_sql = "update [sy_mnu] set [parent_menu_id] = '" + (parent_menu_id == "" ? "" : parent_menu_id) + "', [modified_at] = '" + DateTime.Now.ToUniversalTime().ToString() +
                            "', [modified_by] = '" + HttpContext.Current.Session["user_afrowid"] + "' where [af_row_id] = " + strMenuRowId + " and [pageset_id] = '" + ps_rowkey.Value + "';";
            HDD.ExecuteCmdObj(new SqlCommand(menu_sql));
            sr = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in createMenuForPage. " + e.Message);
        }
    }

    private string getAutoNumberValue(string sObjectTable, string Field)
    {
        HDDatabase HDD = new HDDatabase();
        string sVal = HDD.GetColumnValue("select max([" + Field.Replace("'", "''") + "]) + 1 as AN from [" + sObjectTable.Replace("'", "''") + "]");
        HDD = null;
        sVal = sVal == "" ? "1" : sVal;
        //if (PageRowCount > 1)
        //    sVal = Convert.ToString(Convert.ToInt32(sVal) + PageRowCount - 1);
        return sVal;
    }

    private string getRefURL()
    {
        try
        {
            return "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error: RoleSecurity: getRefURL() : " + ex.Message);
            return "";
        }
    }
    /// <summary>
    /// To set the droplist values for a control.
    /// </summary>
    /// <param name="dtaData">Input data table</param>
    // Added by 'Imran Gani' on 26-Dec-2013, for droplist support.
    private void loadControlDroplist(DataTable dtaData)
    {
        HDDatabase hd = new HDDatabase();
        DataTable dt_droplist = new DataTable();
        try
        {
            dt_droplist = hd.GetDataTable("select * from [sy_pg_ctr_droplist] where [page_id] = '" + pg_rowkey.Value + "';");
            if (dt_droplist.Rows.Count == 0) return;
            foreach (DataRow dr in dtaData.Rows)
            {
                string sDroplistVal = string.Empty;
                foreach (DataRow dr_pl in dt_droplist.Select("control_id = '" + dr["pg_ctr_row_id"].ToString() + "'"))
                {
                    if (!string.IsNullOrEmpty(sDroplistVal))
                        sDroplistVal += System.Environment.NewLine;
                    sDroplistVal += dr_pl["droplist_value"].ToString();
                }
                dr["ta_droplist"] = sDroplistVal;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : loadControlDroplist :" + ex.Message);
        }
        finally
        {
            dt_droplist.Dispose();
            hd = null;
        }
    }
}